How to get primary key value with Entity Framework Core

cResults picture cResults · Jun 7, 2015 · Viewed 17.2k times · Source

We are currently using the method below which depends upon IObjectContextAdapter in an abstract Repository. From what I'm reading, it appears that anything related to ObjectContext is being chopped out of Entity Framework Core. The method below is the only place we depend upon anything related to ObjectContext.

We'd like to upgrade to Entity Framework Core. This is our only road block. Is there a way to get the value of the primary key of an entity with the Entity Framework Core apis?

// Entity Framework
public virtual int GetKey(T entity)
{
    var oContext = ((IObjectContextAdapter)_DbContext).ObjectContext;
    var oSet = oContext.CreateObjectSet<T>();
    var keyName = oSet.EntitySet.ElementType
                                .KeyMembers
                                .Select(k => k.Name)
                                .Single();

    return (int)entity.GetType().GetProperty(keyName).GetValue(entity, null);
}

Answer

YuriyP picture YuriyP · Jan 25, 2016

I also faced with similar problem and found the following solution

// Entity Framework Core
public virtual int GetKey<T>(T entity)
{
    var keyName = Context.Model.FindEntityType(typeof (T)).FindPrimaryKey().Properties
        .Select(x => x.Name).Single();

    return (int)entity.GetType().GetProperty(keyName).GetValue(entity, null);
}