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.
-
Can you share your code? Can you share the exact error/exception that you are getting? Please don't include tags in your title. Is this specific to Entity Framework 5?– Ryan GatesApr 9, 2013 at 4:17
-
Yes it is specific to Entity Framework 5 , thats why I specified it in the title and my actual question.– BreadtruckApr 9, 2013 at 4:31
-
No code because it is just a theoretical question. I have found other ways to get the primary key value of an entity, but I was curious if you could get at it from this path– BreadtruckApr 9, 2013 at 4:37
1 Answer
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.
-
I have seen this snippet of code in some other stackoverflow answers I just thought that maybe with EF 5.0 you could maybe do something like dbEntityEntryObject.Property<EntityKey>(); It seems to me that it would have been nice to expose the EntityKey as a property Apr 9, 2013 at 14:51
-
1I even think it should not be hard to introduce a property
dbEntityEntryObject.EntityKey
. You could submit a change request, or check if it's already there: entityframework.codeplex.com/workitem/list/basic. Apr 9, 2013 at 15:08 -
Thanks, those extension methods will come in handy. I suppose in the end your solution is probably how the ef code base would be changed anyway. Apr 10, 2013 at 8:53
-
Doesn't work at all for me, EF6, model first, T4 templates, this always returns null for objects that are newly created ... solutions? May 14, 2014 at 13:12
-