0

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();

Veverke
  • 9,208
  • 4
  • 51
  • 95

1 Answers1

5

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.

wizzardmr42
  • 1,634
  • 12
  • 22
  • You are right. Indeed it would have no way of knowing which increment is next. I was subconsciously expecting some kind of magic. *This time* I will let go :) – Veverke Oct 12 '15 at 11:42
  • What's the best practice then to get the latest increment in an identity column ? Get the greatest value ? – Veverke Oct 12 '15 at 11:46
  • You'd have to send SQL directly - suggest you see this question or a similar one - http://stackoverflow.com/questions/20805067/how-to-get-the-next-identity-value-from-sql-server – wizzardmr42 Oct 12 '15 at 13:07