Category: Entity Framework

Entity Framework – Re-querying or fetching latest foreign key relationship records

In entity framework, you can often include foreign key or relationship collections in your LINQ request by using the ‘Include’ statement.

For example you may want to get a collection of Customers and their related Invoices. This would look something like:

var customersWithInvoices = DataContext.Customers.Include("Invoices")

However there may be times where this is not possible or you want to ensure that you have the latest related collection or you only want to fetch that collection when you need it.

To do this you need when the related records are a collection and re-query the navigation property for your parent entity (here ‘customer’) we use the Collection() method as follows:

try
{
DataContext.Entry(customer)
.Collection<Invoice>("Invoices")
.Query()
.ToList();
}
catch(Exception e)
{
Console.WriteLine(e);
}

Where ‘Invoices’ is the name of your navigation property. Now you can access the latest related objects.

e.g.

var countOfInvoices = customer.Invoices.Count();

To do this you need for a one-to-one related single entity then use the Reference() method instead as follows (Say we wanted the Country dial code of our customers Country):

DataContext.Entry(customer).Reference<Country>("CountryOfResidence").Query().FirstOrDefault();

Here the navigation property is called ‘CountryOfResidence”.

We can now navigate to the Country entity and get the dial code.

e.g.

var dialCode = customer.CountryOfResidence.DialCode;