你如何获得未知名的DbEntityEntry的EntityKey对象 [英] How do you get a DbEntityEntry EntityKey object with unknown name
问题描述
我不应该能够得到使用的DbEntityEntry的复杂属性方法或属性方法的EntityKey对象。我找不到任何的例子 MSDN ,但我presume,这是可能的实体框架5.我不知道,因为我使用的是通用的存储库接口的实体按键或实体的名称。
Shouldn't I be able to get the EntityKey object using the complex property method or property method for the DbEntityEntry. I couldn't find any examples MSDN, but I presume that this is possible in Entity Framework 5. I Will not know the name of the entity key or entity as I am using a generic repository interface.
推荐答案
如果你有你得到一个 DbEntityEntry
对象的EntityKey
首先找到包裹的ObjectContext
:
If you have a DbEntityEntry
object you get the EntityKey
by first finding the wrapped ObjectContext
:
var oc = ((IObjectContextAdapter)dbContext).ObjectContext;
然后你可以找到
oc.ObjectStateManager.GetObjectStateEntry(dbEntityEntryObject.Entity)
.EntityKey
修改
我创建了两个扩展方法是让你接近你想要什么:
I created two extension methods that get you close to what you want:
public static EntityKey GetEntityKey<T>(this DbContext context, T entity)
where T : class
{
var oc = ((IObjectContextAdapter)context).ObjectContext;
ObjectStateEntry ose;
if (null != entity && oc.ObjectStateManager
.TryGetObjectStateEntry(entity, out ose))
{
return ose.EntityKey;
}
return null;
}
public static EntityKey GetEntityKey<T>( this DbContext context
, DbEntityEntry<T> dbEntityEntry)
where T : class
{
if (dbEntityEntry != null)
{
return GetEntityKey(context, dbEntityEntry.Entity);
}
return null;
}
现在,你可以做
var entityKey = dbContext.GetEntityKey(entity);
或
var entityKey = dbContext.GetEntityKey(dbEntityEntryObject);
运行时会选择正确的过载。
The runtime will pick the right overload.
需要注意的是,你提出的语法( dbEntityEntryObject.Property&LT;&的EntityKey GT;()
)不能当实体具有复合键工作。你必须让的EntityKey
从实体本身。
Note that the syntax that you proposed (dbEntityEntryObject.Property<EntityKey>()
) can't work when the entity has a composite key. You have to get the EntityKey
from the entity itself.
这篇关于你如何获得未知名的DbEntityEntry的EntityKey对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!