Get the primary key value of an arbitrary entity in code first

前端 未结 3 539
小鲜肉
小鲜肉 2020-12-09 18:02

Is there such a method?

object GetPrimaryKeyValue(DbEntityEntry entry);

Or how should it be implemented?

3条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-09 18:44

    You need to cast your DbContext to IObjectContextAdapter so you can access the underlying ObjectContext which gives you access to some more advanced features hidden by DbContext.

    Inside your class which derives DbContext the following method will work.

    object GetPrimaryKeyValue(DbEntityEntry entry)
    {
        var objectStateEntry = ((IObjectContextAdapter)this).ObjectContext.ObjectStateManager.GetObjectStateEntry(entry.Entity);
        return objectStateEntry.EntityKey.EntityKeyValues[0].Value;
    }
    

    If there is more than one key then you should iterate over the EntityKeyValues property.

提交回复
热议问题