How do you get a DbEntityEntry EntityKey object with unknown name

后端 未结 1 1511
南笙
南笙 2020-12-06 06:19

Shouldn\'t I be able to get the EntityKey object using the complex property method or property method for the DbEntityEntry. I couldn\'t find any examples MSDN, but I presum

相关标签:
1条回答
  • 2020-12-06 06:28

    If you have a DbEntityEntry object you get the EntityKey by first finding the wrapped ObjectContext:

    var oc = ((IObjectContextAdapter)dbContext).ObjectContext;
    

    Then you can find the entity key by

    oc.ObjectStateManager.GetObjectStateEntry(dbEntityEntryObject.Entity)
        .EntityKey
    

    EDIT

    I created two extension methods that get you close to what you want:

    public static EntityKey GetEntityKey<T>(this DbContext context, T entity)
        where 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>( this DbContext context
                                           , DbEntityEntry<T> dbEntityEntry)
        where T : class
    {
        if (dbEntityEntry != null)
        {
            return GetEntityKey(context, dbEntityEntry.Entity);
        }
        return null;
    }
    

    Now you can do

    var entityKey = dbContext.GetEntityKey(entity);
    

    or

    var entityKey = dbContext.GetEntityKey(dbEntityEntryObject);
    

    The runtime will pick the right overload.

    Note that the syntax that you proposed (dbEntityEntryObject.Property<EntityKey>()) can't work when the entity has a composite key. You have to get the EntityKey from the entity itself.

    0 讨论(0)
提交回复
热议问题