EntityFramework 6如何通过反射获取身份字段? [英] EntityFramework 6 How to get identity-field with reflection?

查看:205
本文介绍了EntityFramework 6如何通过反射获取身份字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类型参数为T的通用方法,其中T是EF模型中实体的类型. 我需要获取这种类型的识别字段的名称. 我看到了这篇文章:是否可以通过反射或其他方式获取实体ID字段的名称? 但是我不明白Tevin在谈论 EntitySetBase EntityTypeBase 类型时在说什么. 如果 EntityTypeBase 是模型中实体之一的类型,则EF6没有属性 KeyMembers .

I have a generic method with type parameter T, where T is the type of entity in EF model. I need to get the name of identifying field in this type. I saw this article: Is there a way to get entity id-field's name by reflection or whatever? But I can't understand, what Tevin talking about when he talks about EntitySetBase and EntityTypeBase types. If EntityTypeBase is type of one of the entities in model, so then EF6 have no property KeyMembers.

推荐答案

我认为不可能仅通过反射来获取主键.

I don't think it's possible to get the primary keys only by reflection.

首先,让我们了解EF如何确定哪些属性将成为主键,而与顺序/优先级无关

First, let's find out how EF determine which property(ies) that will be primary key(s) regardless of the order / priority

主键的实体框架约定为:

The Entity Framework convention for primary keys is:

  1. 您的类定义了一个名称为"ID"或"Id"的属性
  2. 或类名后跟"ID"或"Id"

我们可以使用GetProperties并比较属性名称.

We can use GetProperties and compare the property name.

var key = type.GetProperties().FirstOrDefault(p => 
    p.Name.Equals("ID", StringComparison.OrdinalIgnoreCase) 
    || p.Name.Equals(type.Name + "ID", StringComparison.OrdinalIgnoreCase));

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