Entity Framework 6 + Generic – Get Primary Key from Entity Framework Context

Entity Framework 6 + Generic – Get Primary Key from Entity Framework Context

 
   using System;
   using System.Collections.Generic;
   using System.Data.Entity;
   using System.Data.Entity.Infrastructure;
   using System.Linq;
   using SoccerDAO;
 
   public class GenericService
   {
      private DbContext context;
 
      public GenericService(string name)
      {
         this.context = new SoccerContext(name);
      }
 
      public List<string> GetPrimaryKey<TEntity>() where TEntity : class
      {
         List<string> keylist = new List<string>();
 
         var objectContext = (this.context as IObjectContextAdapter).ObjectContext;
         var entitySet = objectContext.CreateObjectSet<TEntity>().EntitySet;
 
         var KeyMemebers = entitySet.ElementType.KeyMembers;
 
         foreach(var item in KeyMemebers)
         {
            keylist.Add(item.Name);
         }
 
         return keylist;
      }
   }
 

IObjectContextAdapter is from System.Data.Entity.Infrastructure Namespace ( EntityFramework.dll ).