Entity Framework 4: How to find the primary key?

前端 未结 4 711
萌比男神i
萌比男神i 2020-11-28 11:12

I am trying to create a generic method using EF4 to find the primary key of an object.

example

public string GetPrimaryKey()
{
    ...
}
         


        
4条回答
  •  误落风尘
    2020-11-28 12:00

    I assume many people stop by this post just by looking "Entity framework how to find the primary key?" regardless EF version (like me). So I wanted to mentioned that with EF 6.1, you can also create an extension methods to get the primary key. Following is the example and works perfectly fine.

    PS: I am not 100% sure, if that would work with composite and compound keys tho.

    using System;
    using System.Data.Entity;
    using System.Data.Entity.Core.Metadata.Edm;
    using System.Data.Entity.Infrastructure;
    using System.Linq;
    
    namespace System.Data.Entity
    {
        public static class DbContextExtensions
        {
            public static string[] GetKeyNames(this DbContext context)
                where TEntity : class
            {
                return context.GetKeyNames(typeof(TEntity));
            }
    
            public static string[] GetKeyNames(this DbContext context, Type entityType)
            {
                var metadata = ((IObjectContextAdapter)context).ObjectContext.MetadataWorkspace;
    
                // Get the mapping between CLR types and metadata OSpace
                var objectItemCollection = ((ObjectItemCollection)metadata.GetItemCollection(DataSpace.OSpace));
    
                // Get metadata for given CLR type
                var entityMetadata = metadata
                        .GetItems(DataSpace.OSpace)
                        .Single(e => objectItemCollection.GetClrType(e) == entityType);
    
                return entityMetadata.KeyProperties.Select(p => p.Name).ToArray();
            }
        }
    }
    

    Original Source

提交回复
热议问题