首先获取代码任意实体的主键值 [英] Get the primary key value of an arbitrary entity in code first

查看:410
本文介绍了首先获取代码任意实体的主键值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有这样的方法?

object GetPrimaryKeyValue(DbEntityEntry entry);

或者究竟应该如何实施?

Or how should it be implemented?

推荐答案

您需要转换您的的DbContext IObjectContextAdapter 这样你就可以访问底层的ObjectContext 这使您可以访问由的DbContext

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.

在你的类派生的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;
}

如果有多个键,那么你应该遍历 EntityKeyValues​​ 属性。

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

这篇关于首先获取代码任意实体的主键值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆