Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
255 views
in Technique[技术] by (71.8m points)

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

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 presume that this is possible in Entity Framework 5. I Will not know the name of the entity key or entity as I am using a generic repository interface.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...