.net - Retrieve key values of an entity -


for change logging function, need retrieve primary key value of entity. written audit table table name, , changed property names , old , new values.

i reflect type of particular entity , [key] property. work in case because use code-first, attributes, , single-column keys. i'm not sure runtime performance of (uncached) reflection use.

is there more robust , "official" way value of primary key entity known ef?

please stay latest ef version (6.1.3). cannot use solutions ef 4/5 access deprecated or removed functionality.

code sample:

class myentity1 {     [key]     public guid keycolumn { get; set; }     // ... }  class myentity2 {     [key]     public string entityid { get; set; }     // ... }  class mycontext : dbcontext {     public dbset<myentity1> entities1 { get; set; }     public dbset<myentity2> entities2 { get; set; }      public object getentitykey(object entity)     {         return ???(entity);         // expected: value of property [key]     } } 

ps: using following all-manual workaround, in case looking same solution. it's not simple maintain when new entities added.

public object getentitykey<t>(t entity) {     if (typeof(t) == typeof(myentity1))     {         return ((myentity1)(object)entity).keycolumn;     }     if (typeof(t) == typeof(myentity2))     {         return ((myentity2)(object)entity).entityid;     }     // important: makes aware of new entities     throw new notsupportedexception("the specified entity type not supported."); } 

i can't comment on performance of using reflection can find pk of given entity using reflection , looking [key] attribute (i'm assuming have attribute):

public object getentitykey<t>(t entity) {     return typeof(t).getproperties().where(x => attribute.isdefined(x, typeof(keyattribute))).single().getvalue(entity); } 

Comments

Popular posts from this blog

ruby - Trying to change last to "x"s to 23 -

jquery - Clone last and append item to closest class -

c - Unrecognised emulation mode: elf_i386 on MinGW32 -