实体框架代码第一。查找主键 [英] Entity Framework code first. Find primary key

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

问题描述

如何查找类的属性是实体框架代码的主键第一个实体POCO?

How do I find which property of a class is the primary key of the Entity Framework Code First entity POCO?

请注意Id /类名+ Id是不好的选择。必须有一些方法来挖掘Entity Framework使用的约定并可靠地获取关键属性。

Please note string matching for Id / class name + "Id" is a bad option. There must be some way to dig out the convention used by Entity Framework and reliably getting the key property.

提前感谢。

推荐答案

您可以询问映射元数据以获取关键属性的名称(可以有多于一个):

You can ask mapping metadata to get names of key properties (there can be more then one):

ObjectContext objectContext = ((IObjectContextAdapter)dbContext).ObjectContext;
ObjectSet<YourEntity> set = objectContext.CreateObjectSet<YourEntity>();
IEnumerable<string> keyNames = set.EntitySet.ElementType
                                            .KeyMembers
                                            .Select(k => k.Name);

一旦你有键名,你可以使用反射来访问它们的值。

Once you have key names you can use reflection to access their values.

您可以看到该方法恢复到ObjectContext API,因为DbContext API仅适用于简单的场景,您不需要像这样的细节,例如映射元数据。

As you can see the approach reverts back to ObjectContext API because DbContext API is only for simple scenarios where you don't bother with such details like mapping metadata.

这篇关于实体框架代码第一。查找主键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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