Tag: C#

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:

catch(Exception e)

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


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):


Here the navigation property is called ‘CountryOfResidence”.

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


var dialCode = customer.CountryOfResidence.DialCode;

Understanding CA2214 code analysis warnings using ViewModels

If like me you didn’t understand the the rest of the message and it’s implications here is a simple explanation and answer.

When an object that implements an inherited class (e.g. a ViewModel that inherits from ViewModelBase) is constructed, the constructors in the base class or classes are executed first.

However as the base classes execute methods or events, if these implemented methods or events are overridden, by a more derived class, then the base could call these and not it’s intended base methods. This could cause some unexpected behaviour.

If you make calls to potentially override-able methods yourself (e.g. RaisePropertyChanged) , you probably intended to and know full well what the consequences are. So why the annoying message?

Well, CA2214 is warning you that this may become a problem if anyone decides to inherit from your class (e.g. your ViewModel). As this is probably not something that you want or intend in your project, you can eliminate this warning by simply sealing your class!

    public sealed class MainViewModel : ViewModelBase

This will ensure that your class cannot be inherited from. This should make the warning go away.

If you are writing your own base class or a class that is to be inherited from, then don’t call override-able methods in your constructors!

Hope that helps! hhhmmmmm