【问题标题】:EF 4.1 How to get the first key of an entity - compositeEF 4.1 如何获取实体的第一个键 - 复合
【发布时间】:2012-07-22 22:47:56
【问题描述】:

我有一个类,我有 2 个键(复合键),然后我有我的审计日志功能,我曾经在其中获取实体的主键,如下所示:

string keyName = dbEntry.Entity.GetType().GetProperties().Single(p => p.GetCustomAttributes(typeof(KeyAttribute), false).Count() > 0).Name;

问题是我试图保存的模型之一有一个复合键:

 [Key,Column("paymentdetailid", TypeName = "int", Order=0)]
    public Int32 PaymentDetailId { get; set; }

    [Key,Column("chargedetailid", TypeName = "int", Order=1)]
    public Int32 ChargeDetailId { get; set; }

我在尝试获取 keyName 时遇到以下错误:

Sequence contains more than one matching element 

关于如何解决这个问题的任何线索?我只想拿到第一把钥匙。

谢谢,

解决方案

解决办法是这样的:

var keyNames = dbEntry.Entity.GetType().GetProperties().Where(p => p.GetCustomAttributes(typeof(KeyAttribute), false).Count() > 0).ToList();

字符串 keyName = keyNames[0].Name;

【问题讨论】:

标签: entity-framework entity-framework-4


【解决方案1】:

您只需将Single 替换为First 即可获得具有关键属性的第一个属性:

string keyName = dbEntry.Entity.GetType().GetProperties().First(
    p => p.GetCustomAttributes(typeof(KeyAttribute), false).Any()).Name;

另外,Any()Count() > 0 更简洁,因为它只是说“检查属性 是否有 关键属性”。或者使用FirstOrDefault,如果你想捕捉类型根本没有键属性的情况并抛出适当的异常(FirstOrDefault 将返回null 然后First 将抛出“序列不包含元素”异常):

var property = dbEntry.Entity.GetType().GetProperties().FirstOrDefault(
    p => p.GetCustomAttributes(typeof(KeyAttribute), false).Any());

if (property == null)
    throw new InvalidOperationException(string.Format(
        "Entity {0} has no [Key] attribute.", dbEntry.Entity.GetType().Name));

string keyName = property.Name;

【讨论】:

    猜你喜欢
    • 2021-05-14
    • 2011-10-22
    • 1970-01-01
    • 1970-01-01
    • 2011-07-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多