2012-07-21 53 views
1

我有一個類,我有2個鍵(組合鍵),然後我有我的審計日誌功能,我曾經得到這樣一個實體的主鍵:EF 4.1如何獲得一個實體的第一個關鍵 - 複合

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

的問題是,該模型的一個IM試圖挽救有一個複合鍵:

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

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

即時得到試圖獲得密鑰名時出現以下錯誤:

Sequence contains more than one matching element 

如何解決這個任何線索?我只想得到第一把鑰匙。

謝謝,

SOLUTION

該溶液是這一個:。

VAR鍵名= dbEntry.Entity.GetType()的GetProperties()其中(P => p.GetCustomAttributes (typeof運算(KeyAttribute),假).Count之間()> 0).ToList();

串的keyName =鍵名[0]請將.Name;

+0

也許你不應該使用「單一」,如果你想多一個結果? – Luxspes 2012-07-22 03:57:28

+0

你嘗試過嗎? http://stackoverflow.com/questions/2958921/entity-framework-4-how-to-find-the-primary-key – Luxspes 2012-07-22 04:11:34

+0

你是對的。問題是「單身」。非常感謝 – VAAA 2012-07-22 14:06:22

回答

0

只需更換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; 
相關問題