How to get ObjectSet's entity key name?

后端 未结 7 1370
悲哀的现实
悲哀的现实 2020-12-29 00:08

I\'ve created a generic ObjectSet in my generic repository.

What I would like to get is the name of the EntityKey of ObjectS

7条回答
  •  情话喂你
    2020-12-29 00:33

    I had a tough time trying to do almost the same thing, getting the primary key name and value at runtime when the type is unknown. I was just get trying to implement an auditing scheme for deletes, and every solution i find involves superfluous code that I dont really understand. The EntityKey is not available from a DbContext, which is also confusing and annoying. The last 5 lines may save you 5 hours and 1 yr of baldness. I am not attempting this for Inserts, so if you do, you need to inspect those values carefully as they may be 0 or null.

    foreach(var entry in ChangeTracker.Entries())
    {
    ...
    
    case EntityState.Deleted:
    
    var oc = ((IObjectContextAdapter)this).ObjectContext;  //this is a DbContext
    EntityKey ek = oc.ObjectStateManager.GetObjectStateEntry(entry.Entity).EntityKey;
    var tablename = ek.EntitySetName;
    var primaryKeyField = ek.EntityKeyValues[0].Key;     //assumes only 1 primary key
    var primaryKeyValue = ek.EntityKeyValues[0].Value;
    

提交回复
热议问题