c# - How do you get a DbEntityEntry EntityKey object with unknown name -


shouldn't able entitykey object using complex property method or property method dbentityentry. couldn't find examples msdn, presume possible in entity framework 5. not know name of entity key or entity using generic repository interface.

if have dbentityentry object entitykey first finding wrapped objectcontext:

var oc = ((iobjectcontextadapter)dbcontext).objectcontext; 

then can find entity key by

oc.objectstatemanager.getobjectstateentry(dbentityentryobject.entity)     .entitykey 

edit

i created 2 extension methods close want:

public static entitykey getentitykey<t>(this dbcontext context, t entity)     t : class {     var oc = ((iobjectcontextadapter)context).objectcontext;     objectstateentry ose;     if (null != entity && oc.objectstatemanager                             .trygetobjectstateentry(entity, out ose))     {         return ose.entitykey;     }     return null; }  public static entitykey getentitykey<t>( dbcontext context                                        , dbentityentry<t> dbentityentry)     t : class {     if (dbentityentry != null)     {         return getentitykey(context, dbentityentry.entity);     }     return null; } 

now can do

var entitykey = dbcontext.getentitykey(entity); 

or

var entitykey = dbcontext.getentitykey(dbentityentryobject); 

the runtime pick right overload.

note syntax proposed (dbentityentryobject.property<entitykey>()) can't work when entity has composite key. have entitykey entity itself.


Comments

Popular posts from this blog

android - getbluetoothservice() called with no bluetoothmanagercallback -

sql - ASP.NET SqlDataSource, like on SelectCommand -

ios - Undefined symbols for architecture armv7: "_OBJC_CLASS_$_SSZipArchive" -