Home United States USA — software Entity Framework: new () vs. DbSet. Create () Entity Framework: new ()...

Entity Framework: new () vs. DbSet. Create () Entity Framework: new () vs. DbSet. Create ()

331
0
SHARE

For Entity Framework users, new () and DbSet. Create () are both used for entity instantiation, but lazy loading will determine when do use which one.
This is one of those “I had to explain this couple times already so next time, I want something I can redirect people to” kind of post.
What I want to write about is the difference in behavior between using new () and DbSet. Create () for instantiating new entities. In order to do this, I’ve created a very simple model and context:
I’ve also created a very simple view that lists characters already present in the database and allows for adding new ones.
The view is powered by the following ViewModel and controller.
The AddCharacter method is the point of interest here. There are two ways to implement it, and they will result in a different behavior.
Following the first Entity Framework tutorial that pops up on Google will result in code similar to this:
In order to be able to create new entities as proper dynamic proxies, the DbSet class provides the Create method. This method returns a new dynamic proxy instance that isn’t added or attached to the context. To use it, only a single line of code needs to be changed.
After this simple change, the code works as expected — related entities are being lazy loaded when needed.
The sample above is built in a way that highlights the difference between new () and DbSet. Create () (it even has an N+1 selects hiding in there for the sake of simplicity) . In real life, this rarely causes an issue, as there are a couple of other things that can impact the behavior (related entity already present in context or usage of the Include () method, for example) . But when this causes an issue, it’s always unexpected, and I’ve seen smart people struggling to wrap their heads around what is going on. It is important to understand the difference and use both mechanisms appropriately (sometimes lack of lazy loading may be desired) .

Continue reading...