添加时获取DBEntityEntry的主键

时间:2014-09-09 16:21:51

标签: c# entity-framework entity-framework-5 primary-key

我正在尝试获取我在EF5应用程序中插入,更新或删除的每个条目的主键信息。我使用类似的代码:

//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)";
}

但是,此代码的问题在于,当将新记录插入数据库时​​,它无法正常工作。当条目状态为EntityState.Added时,key.EntityKeyValues具有空值(此代码将keyName的值设置为&#34;(NotFound)&#34;。

有没有办法在插入记录时获取主键的列名?

2 个答案:

答案 0 :(得分:9)

我找到了一种方法,将原始代码与Gert发布​​的链接中的代码相结合:

//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)";
}

到目前为止,即使我添加了新记录,它似乎也在起作用。

答案 1 :(得分:0)

在SaveChanges()之后,您的主键就位。您可以在SaveChanges()之前保留changedList,然后在SaveChanges()之后保存更改日志。

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