How to get the Primary Key(s) in Entity Framework 4.1, i.e. using DbContext

后端 未结 5 1888
逝去的感伤
逝去的感伤 2020-12-29 08:52

The answers I\'m seeing here are for ObjectContext. Is there a property to determine an entity\'s primary key names when using DbContext?

Ah.. one of those times tha

5条回答
  •  無奈伤痛
    2020-12-29 09:40

    The solution proposed by Ladislav Mrnka won't work for derived entities as You can't create an object set for a derived type. You'll see this error :

    ArgumentException: There are no EntitySets defined for the specified entity type ... If ... is a derived type, use the base type instead. Parameter name: TEntity

    Here is my solution avoiding creating an object set :

    public string[] GetEntityKeyNames(DbContext context)
    {
        if (context == null)
        {
            throw new ArgumentNullException("context");
        }
        var objectContext = ((IObjectContextAdapter)Context).ObjectContext;
        //We must use the namespace of the context and the type name of the entity
        string entityTypeName = context.GetType().Namespace + '.' + typeof(TEntity).Name;
        var entityType = objectContext.MetadataWorkspace.GetItem(entityTypeName, DataSpace.CSpace);
        return entityType.KeyProperties.Select(k => k.Name).ToArray();
    }
    

提交回复
热议问题