Entity Framework 6 + Generic – Remove Item By Table Primary Key

Entity Framework 6 + Generic – Remove Item By Table Primary Key

 
   using System;
   using System.Collections.Generic;
   using System.Data.Entity;
   using System.Data.Entity.Infrastructure;
   using System.Linq;
   using System.Linq.Dynamic;
   using SoccerDAO;
 
   public class GenericService
   {
      internal DbContext context;
 
      public GenericService(string name)
      {
         this.context = new Soccer(name);
      }
 
      … …
 
      public int RemoveItem<TEntity>(int id) where TEntity : class
      {
         DbSet<TEntity> db_set = context.Set<TEntity>();
 
         string key = GetPrimaryKey<TEntity>().First();
 
         if (key != null)
         {
            string query = String.Format("{0} == {1}", key, id.ToString());
 
            TEntity item = db_set.Where(query).FirstOrDefault();
 
            if (item != null)
            {
               db_set.Remove(item);
               this.context.SaveChanges();
               return 1;
            }
            else
            {
               return 0;
            }
         }
         else
         {
            return 0;
         }
      }
 
      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;
      }
   }