0

我正在这样做:

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);
        }
    }
4

1 回答 1

3

DbSet.Include()返回一个DbSet<T>包含该导航属性的新值。
由于您不使用返回的 DbSet,因此您的Include()调用无效。

您需要将结果分配给Include()局部变量并使用它而不是DbSet.

于 2012-09-23T16:09:55.427 回答