Get DBEntityEntry primary key when adding

I am trying to get primary key information for every record that I insert, update or delete in an EF5 application. I am using code like this:

//Get collection of each insert, update, or delete made on the entity. IEnumerable<DbEntityEntry> changedEntries = this.ChangeTracker.Entries() .Where(e => e.State == EntityState.Added || e.State == EntityState.Modified || e.State == EntityState.Deleted); foreach (DbEntityEntry entry in changedEntries) { //Get primary key collection EntityKey key = ((IObjectContextAdapter)this).ObjectContext.ObjectStateManager .GetObjectStateEntry(entry.Entity).EntityKey; string keyName; //Get name of first key. Make sure a collection was returned. if (key.EntityKeyValues != null) keyName = key.EntityKeyValues[0].Key; else keyName = "(NotFound)"; } 

The problem with this code, however, is that it does not work when a new record is inserted into the database. When the state of the entry is EntityState.Added, the key .EntityKeyValues ​​has a value of zero (this code sets the value of keyName to "(NotFound)".

Is there a way to get the column name for the primary key when inserting a record?

+5
source share
2 answers

I figured out a way to do this by combining my original code with the code from the Gert link:

 //Get collection of each insert, update, or delete made on the entity. IEnumerable<DbEntityEntry> changedEntries = this.ChangeTracker.Entries() .Where(e => e.State == EntityState.Added || e.State == EntityState.Modified || e.State == EntityState.Deleted); foreach (DbEntityEntry entry in changedEntries) { EntitySetBase setBase = ObjectContext.ObjectStateManager .GetObjectStateEntry(entry.Entity).EntitySet; string[] keyNames = setBase.ElementType.KeyMembers.Select(k => k.Name).ToArray(); string keyName; if (keyNames != null) keyName = keyNames.FirstOrDefault(); else keyName = "(NotFound)"; } 

While this works, even when I add a new entry.

+9
source

After saving SaveChanges (), your primary key is in place. You can save changeList before SaveChanges (), and then save the change log after SaveChanges ().

Ref http://webmisterradixlecti.blogspot.co.nz/2013/04/get-primary-key-on-insert-using-entity.html

0
source

Source: https://habr.com/ru/post/1202171/


All Articles