none
How to make a Generic method for this? RRS feed

  • Question

  •  public static int Insert(Model.ItemMaster entity) {
        using (Model.Entities ae1 = new Model.Entities())
        {
            ae1.Set(typeof(Model.ItemMaster)).Add(entity);
            return  ae1.SaveChanges();
                
        }
                
    }

    Given the code above I am wanting to abstract this insert method.  But I don't want to pass in a specific class of type Model.ItemMaster as the entity, I want to pass in any class that was generated from any of the tables I imported using EF5.0.  How would I abstract that?

    JP Cowboy Coders Unite!


    Monday, November 5, 2012 6:17 PM

All replies

  • Hi,

    Please see the following code snippet. You can also apply the Repository pattern and make a generic class to perform CRUD operations. Please see my blog link as well. http://ovaismehboob.wordpress.com/2012/10/13/implementing-repository-pattern-with-entity-framework-code-first-model-approach/

    public static int Insert<T>(T TObject) where T : class
    {
       Model.Entities ae1=new Model.Entities();   
       var newEntry = ae1.Set<T>().Add(TObject);
       return ae1.SaveChanges();
    }
    Hope it helps!


    Ovais Mehboob

    Tuesday, November 6, 2012 5:00 AM
  • Thanks Ovais: I reformatted and removed compile errors from example on your site.  This code works in C# and EF 4.0  where there is a Service in the project.

     public class Repository : IRepository
        {
            private DbContext Context;
    
            public Repository(string nameOrConnectionString)
            {
                Context = new DbContext(nameOrConnectionString);
            }
    
            public Repository(DbContext context)
            {
                Context = context;
            }
    
            public void CommitChanges()
            {
                Context.SaveChanges();
            }
    
            public T Single<T>(Expression<Func<T, bool>> expression) where T : class
            {
                return All<T>().FirstOrDefault(expression);
            }
    
            public IQueryable<T> All<T>() where T : class
            {
                return Context.Set<T>().AsQueryable();
            }
    
            public virtual IQueryable<T> Filter<T>(Expression<Func<T, bool>> predicate) where T : class
            {
                return Context.Set<T>().Where<T>(predicate).AsQueryable<T>();
            }
    
            public virtual IQueryable<T> Filter<T>(Expression<Func<T, bool>> filter, out  int total, int index = 0, int size = 50) where T : class
            {
                int skipCount = index * size;
                var _resetSet = filter != null ? Context.Set<T>().Where(filter).AsQueryable() : Context.Set<T>().AsQueryable();
                _resetSet = skipCount == 0 ? _resetSet.Take(size) : _resetSet.Skip(skipCount).Take(size);
                total = _resetSet.Count();
                return _resetSet.AsQueryable();
            }
    
            public virtual T Create<T>(T TObject) where T : class
            {
                var newEntry = Context.Set<T>().Add(TObject);
                Context.SaveChanges();
                return newEntry;
            }
    
            public virtual int Delete<T>(T TObject) where T : class
            {
                Context.Set<T>().Remove(TObject);
                return Context.SaveChanges();
            }
    
            public virtual int Update<T>(T TObject) where T : class
            {
                try
                {
                    var entry = Context.Entry(TObject);
                    Context.Set<T>().Attach(TObject);
                    entry.State = EntityState.Modified;
                    return Context.SaveChanges();
                }
                catch (OptimisticConcurrencyException ex)
                {
                    throw ex;
                }
            }
    
            public virtual int Delete<T>(Expression<Func<T, bool>> predicate) where T : class
            {
                var objects = Filter<T>(predicate);
                foreach (var obj in objects)
                    Context.Set<T>().Remove(obj);
                return Context.SaveChanges();
            }
    
            public bool Contains<T>(Expression<Func<T, bool>> predicate) where T : class
            {
                return Context.Set<T>().Count<T>(predicate) > 0;
            }
    
            public virtual T Find<T>(params  object[] keys) where T : class
            {
                return (T)Context.Set<T>().Find(keys);
            }
    
            public virtual T Find<T>(Expression<Func<T, bool>> predicate) where T : class
            {
                return Context.Set<T>().FirstOrDefault<T>(predicate);
            }
    
            public virtual void ExecuteProcedure(String procedureCommand, params  SqlParameter[] sqlParams)
            {
                Context.Database.ExecuteSqlCommand(procedureCommand, sqlParams);
            }
    
            public virtual void SaveChanges()
            {
                Context.SaveChanges();
            }
    
            public void Dispose()
            {
                if (Context != null)
                    Context.Dispose();
            }
        }

    And:

      public interface IRepository : IDisposable
        {
            /// <summary>
            /// Gets all objects from database
            /// </summary>
            /// <returns>IQueryable of type T</returns>
    
            IQueryable<T> All<T>() where T : class;
    
            /// <summary>
            /// Gets objects from database by filter.
            /// </summary>
            ///<public param name=”predicate”>public Specified a filter</param>
            /// <returns>IQueryable of type T</returns>
    
            IQueryable<T> Filter<T>(Expression<Func<T, bool>> predicate) where T : class;
    
            /// <summary>
            /// Gets objects from database with filting and paging.
            /// </summary>
            /// <public typeparam name=”Key”>
            /// <public param name=”filter”>public Specified a filter</param>
            /// <public param name=”total”>public Returns the public total records public count of the filter.</param>
            /// <public param name=”index”>public Specified the page index.</param>
            /// <public param name=”size”>public Specified the page size</param>
            /// <returns></returns>
    
            IQueryable<T> Filter<T>(Expression<Func<T, bool>> filter, out  int total, int index = 0, int size = 50) where T : class;
    
            /// <summary>
            /// Gets the object(s) is exists in database by specified filter.
            /// </summary>
            /// <public param name=”predicate”>public Specified the filter expression</param>
            /// <returns></returns>
    
            bool Contains<T>(Expression<Func<T, bool>> predicate) where T : class;
    
            /// <summary>
            /// Find object by keys.
            /// </summary>
            /// <public param name=”keys”>public Specified the search keys.</param>
            /// <returns></returns>
    
            T Find<T>(params  object[] keys) where T : class;
    
            /// <summary>
            /// Find object by specified expression.
            /// </summary>
            /// <public param name=”predicate”></param>
            /// <returns></returns>
    
            T Find<T>(Expression<Func<T, bool>> predicate) where T : class;
    
            /// <summary>
            /// Create a new object to database.
            /// </summary>
            /// <public param name=”t”>public Specified a public new object to create.</param>
            /// <returns></returns>
    
            T Create<T>(T t) where T : class;
    
            /// <summary>
            /// Delete the object from database.
            /// </summary>
            /// <public param name=”t”>public Specified a existing public object to delete.</param>
    
            int Delete<T>(T t) where T : class;
    
            /// <summary>
            /// Delete objects from database by specified filter expression.
            /// </summary>
            /// <public param name=”predicate”></param>
            /// <returns></returns>
    
            int Delete<T>(Expression<Func<T, bool>> predicate) where T : class;
    
            /// <summary>
            /// Update object changes and save to database.
            /// </summary>
            /// <public param name=”t”>public Specified the public object to save.</param>
            /// <returns></returns>
    
            int Update<T>(T t) where T : class;
    
            /// <summary>
            /// Select Single Item by specified expression.
            /// </summary>
            /// <public typeparam name=”T”></typeparam>
            /// <public param name=”expression”></param>
            /// <returns></returns>
    
            T Single<T>(Expression<Func<T, bool>> expression) where T : class;
    
            void SaveChanges();
    
            void ExecuteProcedure(String procedureCommand, params  SqlParameter[] sqlParams);
        }


    JP Cowboy Coders Unite!


    Tuesday, November 6, 2012 3:45 PM
  • I'll test today and post back results.

    JP Cowboy Coders Unite!

    Tuesday, November 6, 2012 3:45 PM
  • JP, you're welcome!

    The code I have shared on my website have no compile time errors and it works fine with C# and EF 4.3.1.0. I am using it in some project currently but thanks for reformatting here on the forum. Keep us posted with the results.


    Ovais Mehboob

    Tuesday, November 6, 2012 5:49 PM
  • Ovais;

    With this I am getting no results:

    public IQueryable<ItemMaster> FilterContains(string Contains)
    {
        using (var ae = new MyEntities())
        {
            var REPIM = new Repository(ae);
            var stuff = REPIM.Filter<ItemMaster>(p => p.itnbr.ToLower().Contains(Contains.ToLower()));
            return stuff;
        }
    }
    I've tried altering the Lambda to try everything. NOTE I can get this to work without the repository code. Any suggestions?

    JP Cowboy Coders Unite!

    Wednesday, November 7, 2012 7:41 PM
  • Do I have to pass in a LINQ Expression or is the Lamba ok?

    JP Cowboy Coders Unite!

    Wednesday, November 7, 2012 7:42 PM
  • Please try following. Normally we used contains when we have a list of strings and we need to fetch the rows based on that list and comparing with particular column.

    var stuff = REPIM.Filter<ItemMaster>(p=> new String[]{Contains}.Contains(p.itnbr));

    Hope this helps!


    Ovais Mehboob

    Thursday, November 8, 2012 6:47 AM
  • Please clarify:

    //This example works when not using Repository pattern.

    MyEntities ae = new MyEntities(); var stuff = ae.EntityCollection.Where(p => p.ITEMID.Contains("ATP"));

    //Attempting to inject the repository pattern using same lamba, this fails.

    var REPIM = new Repository(ae); var stuff = REPIM.Filter<EntityType>(p => p.ITEMID.Contains("ATP"));



    JP Cowboy Coders Unite!



    Thursday, November 8, 2012 3:25 PM
  • Could it be that I don't understand filter?  What I want to do is go to the database and get all entities with the criteria of "ATP"...in this example.

    JP Cowboy Coders Unite!

    Thursday, November 8, 2012 3:29 PM
  • JP,

    I have tested this once more and its working. I am using filter like below and its returning the desired results.

    var result= context.Repository.Filter<User>(i => i.UserName.Contains("ovais")).First();

    It should work in your case too. Please debug and share your results exactly if its not working.


    Ovais Mehboob

    Thursday, November 8, 2012 6:32 PM
  • Thanks I made a mistake in the field name I was filtering on, thus the zero records.

    Second Question: How do I get this one to work?

           public T Find<T>(System.Linq.Expressions.Expression<System.Func<T, bool>> predicate) where T : class
            {
                using (var ae = new Entities()) {
                  var stuff =  ae.ItemMasters.Where(predicate);
                  return stuff as T;
                }
            }
    the ae.ItemMasters returns a DBSet, and the error message is that it doesn't like the predicate.  Mostly because it knows that the ae.ItemMasters collection is not generic (I think)...  So this statement above won't even compile.

    JP Cowboy Coders Unite!


    Thursday, November 8, 2012 10:17 PM