2012-09-23 237 views
0

我這樣做:實體框架System.ObjectDisposedException

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

回答

3

DbSet.Include()返回一個新DbSet<T>這包括導航屬性。
由於您不使用返回的DbSet,因此您的Include()調用不起作用。

您需要將Include()的結果分配給局部變量,並使用該變量代替DbSet

+0

謝謝。有用。 – gigi