Friday, July 8, 2016

Why Entity Framework POCO class properties should be marked "virtual"

I had always wondered why Entity Framework would generate all of my POCO classes decorated with the virtual keyword for all of the class attributes, when many code samples using Entity Framework never used the virtual keyword at all!

Well, I soon found the answer in this MSDN article:

As it turns out, marking the attributes as virtual is a deliberate decision on the part of Microsoft in order to better support Unit Testing and Mocking!

Therefore, if you want to support Unit Testing and Mocking in your own Entity Framework implementations (and I am guessing that you do), then you will want to mark these attributes virtual as well!

No comments:

Post a Comment