【问题标题】:Find KeyAttribute of a class, defined using HasKey method查找使用 HasKey 方法定义的类的 KeyAttribute
【发布时间】:2015-02-20 15:41:48
【问题描述】:

我正在使用 Entity Framework Power Tools 来生成数据库模型类。 它使用 HasKey() 方法来定义类的 Key Attribute。 在我的应用程序代码中使用它时,有什么方法可以找到我的类的关键属性? 有什么方法可以检查特定属性是否为关键属性?

public class MyTableMap : EntityTypeConfiguration<MyTable>
{
   public MyTableMap()
   {
       // Primary Key
       this.HasKey(t => t.RecordID);
   }
 }

我正在尝试使用以下方法查找关键属性,但它不起作用

if (propertyInfoObj.GetCustomAttributes(false).Any(x => x.GetType() == typeof(KeyAttribute)))

【问题讨论】:

  • “但它不工作” - 错误信息?

标签: c# entity-framework attributes key


【解决方案1】:

我使用以下方法解决了我的问题:

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

            string keyName = keyNames.FirstOrDefault();

对象属性和/或值可以通过 keyName 使用反射来访问。

【讨论】:

    猜你喜欢
    • 2014-11-03
    • 1970-01-01
    • 2021-12-30
    • 1970-01-01
    • 2013-06-25
    • 1970-01-01
    • 1970-01-01
    • 2017-10-19
    • 1970-01-01
    相关资源
    最近更新 更多