实体框架System.ObjectDisposedException

时间:2012-09-23 16:08:34

标签: .net entity-framework

我这样做:

User user = _usersRepository.SingleOrDefault(u => u.Username == "gigi", new string[] { "Roles" });
UnitOfWork.Current.Dispose();

我没有得到与该用户相关的角色,我得到了System.ObjectDisposedException。

如果不是进行存储库调用,我只需执行:

            User user;
            using (MyEntities ctx = new MyEntities ())
            {
                user = ctx.Users.Include("Roles").SingleOrDefault(u => u.Username == "gigi");
            }

我确实得到了这些角色。 我错过了什么?

LE:这就是我的基础知识库的样子:

    public class BaseRepository<T> : IBaseRepository<T> where T : class
    {
        private DbContext _context;
        private IDbSet<T> _dbSet;

        protected DbContext Context
        {
            get
            {
                if (_context == null)
                {
                    EFUnitOfWork currentUnitOfWork = (EFUnitOfWork)UnitOfWork.Current;
                    _context = currentUnitOfWork.Context;
                }

                return _context;
            }
        }

        protected IDbSet<T> DbSet
        {
            get
            {
                if (_dbSet == null)
                {
                    _dbSet = Context.Set<T>();
                }

                return _dbSet;
            }
        }

        public void Add(T entity)
        {
            DbSet.Add(entity);
        }

        public void Attach(T entity)
        {
            DbSet.Attach(entity);
        }

        public void Delete(T entity)
        {
            DbSet.Remove(entity);
        }

        public void Update(T entity)
        {
            Context.Entry(entity).State = System.Data.EntityState.Modified;
        }

        public T SingleOrDefault(Expression<Func<T, bool>> where, string[] includes=null)
        {            
            if (includes != null)
            {
                foreach (string property in includes)
                {
                    DbSet.Include(property);
                }
            }
            return DbSet.SingleOrDefault(where);
        }

        public IQueryable<T> Get(Expression<Func<T, bool>> where, string[] includes=null)
        {
            if (includes != null)
            {
                foreach (string property in includes)
                {
                    DbSet.Include(property);
                }
            }
            return DbSet.Where(where);
        }
    }

1 个答案:

答案 0 :(得分:3)

DbSet.Include()会返回包含该导航属性的新DbSet<T> 由于您未使用返回的DbSet,因此Include()来电无效。

您需要将Include()的结果分配给局部变量并使用该变量代替DbSet