Veverke
Veverke

Reputation: 11358

What's the purpose of DbSet.Create() if not to properly initialize the identity columns?

In working with Entity Framework Database First,

why is it that issuing the Create method in any of my DbContext Sets creates an instance of the set's entity without incrementing its Identity columns ?

Considering I build all entities I want to add to a given set first, and only once, at the end, I add them all via DbContext.SaveChanges() - what's really the use of DbSet.Create() if not to property initialize the identity columns ? I could simply manually instantiate my DbSet as var newEntity = new MyClass();

Upvotes: 0

Views: 601

Answers (1)

wizzardmr42
wizzardmr42

Reputation: 1644

It wouldn't make sense for it to increment identity columns since you haven't yet SavedChanges and you might not.

What it actually does is create a new instance and wraps it in a proxy object which is what is returned. The proxy object allows it to keep track of when you access properties on the class, which means that it can update navigation properties (for lazy loading) when you set the relevant foreign key ID property.

See https://msdn.microsoft.com/en-us/data/jj592886.aspx for more information.

Upvotes: 5

Related Questions