I am doing this:
User user = _usersRepository.SingleOrDefault(u => u.Username == "gigi", new string[] { "Roles" });
UnitOfWork.Current.Dispose();
and i don’t get the roles associated to that user, i get that System.ObjectDisposedException.
If instead of doing that repository call , i simply do:
User user;
using (MyEntities ctx = new MyEntities ())
{
user = ctx.Users.Include("Roles").SingleOrDefault(u => u.Username == "gigi");
}
i do get the roles.
What am i missing?
LE:This is how my base repository looks like:
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);
}
}
DbSet.Include()returns a newDbSet<T>that includes that navigation property.Since you don’t use the returned DbSet, your
Include()calls have no effect.You need to assign the result of
Include()to a local variable and use that instead ofDbSet.