locked
Entity framework help RRS feed

  • Question

  • Hello guys. I create a little class for work with my db(many table)

     public class BaseRepository<T> : IRepo<T> where T : class
        {
            #region Fields
    
            private LibraryContext _context;
            private DbSet<T> _dbSet;
    
            #endregion
    
            #region Constructor
    
            public BaseRepository()
            {
                _context = new LibraryContext();
                _dbSet = _context.Set<T>();
            }
    
            #endregion
    
            //Sync----------------------------------------------------------------------------------------------------------------
            public void Insert(T entity)
            {
                _dbSet.Add(entity);
            }
    
            public void Update(T entity)
            {
                _dbSet.Attach(entity);
                _context.Entry(entity).State = EntityState.Modified;
            }
    
            public void Delete(T entity)
            {
                _dbSet.Remove(entity);
            }
    
            public void Delete(Expression<Func<T, bool>> @where)
            {
                IEnumerable<T> objects = _dbSet.Where(where).AsEnumerable();
                foreach (T obj in objects)
                {
                    _dbSet.Remove(obj);
                }
            }
    
            public IEnumerable<T> GetAll()
            {
                return _dbSet.ToList();
            }
    
            public IEnumerable<T> GetMany(Expression<Func<T, bool>> @where)
            {
                return _dbSet.Where(@where).ToList();
            }
    
            public T Get(Expression<Func<T, bool>> @where)
            {
                return _dbSet.Where(@where).FirstOrDefault();
            }
    
            public T GetById(int id)
            {
                return _dbSet.Find(id);
            }
    
            public int Count(Expression<Func<T, bool>> @where = null)
            {
                return _dbSet.Count(@where);
            }
    
            public void Save()
            {
                try
                {
                    _context.SaveChanges();
                }
                catch (DbEntityValidationException e)
                {
                    foreach (var eve in e.EntityValidationErrors)
                    {
                        Console.WriteLine("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:",
                            eve.Entry.Entity.GetType().Name, eve.Entry.State);
                        foreach (var ve in eve.ValidationErrors)
                        {
                            Console.WriteLine("- Property: \"{0}\", Error: \"{1}\"",
                                ve.PropertyName, ve.ErrorMessage);
                        }
                        throw;
                    }
                }
    
            }

    please tell me which way best?(create one context for my app or use my solution create new class for every table??)

    • Moved by CoolDadTx Monday, November 16, 2015 3:46 PM EF related
    Monday, November 16, 2015 11:59 AM

Answers

  • You're really reinventing the wheel here. Is there a particular reason why you're defining your own repository when EF already has that functionality built in?  You are going to end up writing extra code that does nothing but defer to EF's implementation and you'll lose some of the benefits of EF.  In EF the DbContext is the unit of work and IDbSet<T> is the repository.  Extension methods off EF would allow you to mostly accomplish the same thing without having to write code. Note that repositories are useful when you want to hide EF from the rest of your app but if you don't know EF yet then you shouldn't start out this way.

    Since the DbContext is the UoW you should generally have a single instance per "request".  Any changes made by repositories will be applied in the context of the UoW. This allows you to make changes across repositories and then apply/rollback all of them at once. In this architecture the context is the parent and the repositories are the children. Hence the context lifetime is managed by the client code whereas the repositories simply rely on the existence of the context. In many implementations the context is a parameter to the constructor. When the context goes away so do all the repositories.

    Michael Taylor
    http://blogs.msmvps.com/p3net

    Monday, November 16, 2015 3:46 PM

All replies

  • or how change my class that create once
    Monday, November 16, 2015 12:00 PM
  • HI.

    Create a new DbContext instance.

    do some logic executing.

    and finally dispose the context

    please use using statement

    using(var _context = new LibraryContext())
    {
    
    ///do some entity operation executing here
    
    }


    DON'T TRY SO HARD,THE BEST THINGS COME WHEN YOU LEAST EXPECT THEM TO.

    Monday, November 16, 2015 1:24 PM
  •   public void Delete<T>(T entity) where T : class
            {
    
                    _context.Entry(entity).State = EntityState.Deleted;
                    _context.Set<T>().Remove(entity);
                    _context.SaveChanges();
                
                
                
            }
    maybe this solution?
    Monday, November 16, 2015 3:07 PM
  • You're really reinventing the wheel here. Is there a particular reason why you're defining your own repository when EF already has that functionality built in?  You are going to end up writing extra code that does nothing but defer to EF's implementation and you'll lose some of the benefits of EF.  In EF the DbContext is the unit of work and IDbSet<T> is the repository.  Extension methods off EF would allow you to mostly accomplish the same thing without having to write code. Note that repositories are useful when you want to hide EF from the rest of your app but if you don't know EF yet then you shouldn't start out this way.

    Since the DbContext is the UoW you should generally have a single instance per "request".  Any changes made by repositories will be applied in the context of the UoW. This allows you to make changes across repositories and then apply/rollback all of them at once. In this architecture the context is the parent and the repositories are the children. Hence the context lifetime is managed by the client code whereas the repositories simply rely on the existence of the context. In many implementations the context is a parameter to the constructor. When the context goes away so do all the repositories.

    Michael Taylor
    http://blogs.msmvps.com/p3net

    Monday, November 16, 2015 3:46 PM