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);
}
}
謝謝。有用。 – gigi