CA2214 & Entity Framework

I’ve just submitted a comment to the CA2214 code analysis guidance. Posting it here just in case others come across this and wonder what they should do.

There are some circumstances where, using Microsoft’s supplied frameworks this is unavoidable. For example, lets say that I am using Entity Framework:

public class Client
public Client(string name, User ownedBy)
Name = name;
OwnedBy = ownedBy;
protected Client()
public string Name { get; protected set; }
public virtual User OwnedBy { get; protected set; }

In order for Entity Framework to lazy load the OwnedBy property it needs to be marked as virtual. However we might want to stop developers constructing the object without providing the minimum mandatory information (in this case a name string, and a User instance who owns the object). When doing this the CA2214 code analysis warning is fired. The simple solution (in theory) is to mark the Client class as sealed, however Entity framework needs a default constructor to call. The way it works is by inheriting from the Client class with a default constructor which points to the protected constructor, thus allowing it to inject the code to traverse lazy loaded properties/collections etc.

I believe that whilst the guidance provided by CA2214 is valuable, it is inappropriate to say “Do not suppress a warning from this rule” because in some cases you might need to do it by design. Given the proliferation of ORM tools which use this approach for lazy loading of properties the guidance should be updated to outline some scenarios where you might want to call a virtual member.


1 thought on “CA2214 & Entity Framework

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s