I am trying to create a generic method using EF4 to find the primary key of an object.
example
public string GetPrimaryKey()
{
...
}
>
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