1

I have a Class where I have 2 Keys (Composite Keys), then I have my audit log function where I used to get the primary key of an entity like this:

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

The problem is that one of the models im trying to save have a composite key:

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

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

Im getting the following error when trying to get the keyName:

Sequence contains more than one matching element 

Any clue on how to solve this? I just want to get the first key.

Thanks,

SOLUTION

The solution is this one:

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

string keyName = keyNames[0].Name;

VAAA
  • 14,531
  • 28
  • 130
  • 253

1 Answers1

0

You can just replace Single by First to get the first property with a key attribute:

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

Also Any() is a bit cleaner than Count() > 0 as it just says "check if the property has a key attribute". Or use FirstOrDefault if you want to catch the case that the type has no key attribute at all and throw an appropriate exception (FirstOrDefault will return null then whereas First will throw a "Sequence contains no element" exception):

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;
Slauma
  • 175,098
  • 59
  • 401
  • 420