user441521 user441521 - 4 months ago 33
C# Question

Entity Types aren't marked virtual in existing project

I'm trying to mock (using Moq) DbSet's in the DbContext in an existing project that I think was upgraded from VS 2012. I'm getting an error and it's because those DbSet<>'s aren't marked as virtual so they can't be mocked. When I look at newer projects I've done they are marked as virtual.

Since this is in the .edmx file I can't just add virtual to the code since it's autogenerated. Does anyone know any properties that I can set to make them virtual?


In EF6, by default, DBSet members are created as virtual. This cannot be changed from configuration, but T4 template (.tt file) must be edited. Most likely someone edited it before and removed the virtual keyword.

To find your T4 template, expand the tree created by .edmx file in Solution Explorer. You will find a .tt file in it.

To make your DBSets virtual again, you need to find a method string DbSet(EntitySet entitySet) (in default .tt, it is line 307). This method create a property declaration and you can manipulate its pattern here. By default,

"{0} virtual DbSet<{1}> {2} {{ get; set; }}"

is used. Find your version of this pattern and change it to your liking (or simply a default version I provided).

EDIT: If you cannot find this method easily, try searching for


EDIT: After editing and saving .tt file, it should be executed automatically. If not, try right-clicking it and selecting 'Run Custom Tool'.