我有一个看起来像这样的基本存储库:
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 IQueryable<T> Get(string[] includes=null)
{
IQueryable<T> set = DbSet;
if (includes != null)
{
foreach (string include in includes)
{
set = set.Include(include);
}
}
return set;
}
User user = _usersRepository.Get().SingleOrDefault(u => u.Username == "gigi");
这将返回没有 Roles 属性的用户,这没关系。User user = _usersRepository.Get(new string[] { "Roles" }).SingleOrDefault(u => u.Username == "gigi");
这将返回用户和 Roles 属性,这没关系。List<User> users = _usersRepository.Get().Where(u => u.Username.StartsWith("gi")).ToList();
List<User> users = _usersRepository.Get(new string[] { "Roles" }).Where(u => u.Username.StartsWith("gi")).ToList();
查询 3 和 4 都返回具有 Roles 属性的用户列表。为什么查询 3 返回角色?
LE:这是调用,我在上下文处理后检查用户集合。
List<User> users = _usersRepository.Get().Where(u => u.Username.StartsWith("gi")).ToList();
UnitOfWork.Current.Dispose();
LE2:我分别做了同样的事情:
List<User> users; using (MyEntities ctx = new MyEntities ()) { users= ctx.Users.ToList(); }
List<User> users; using (MyEntities ctx = new MyEntities ()) { users= ctx.Users.Include("Roles").ToList(); }
在第一种情况下,没有加载角色,在第二种情况下,它们是可以的。
我没有看到我在存储库示例中做错了什么。
LE3:这是工作单元
public class UnitOfWork
{
private const string HTTPCONTEXTKEY = "Repository.Key";
private static IUnitOfWorkFactory _unitOfWorkFactory;
private static readonly Hashtable _threads = new Hashtable();
public static IUnitOfWork Current
{
get
{
IUnitOfWork unitOfWork = GetUnitOfWork();
if (unitOfWork == null)
{
_unitOfWorkFactory = ObjectFactory.GetInstance<IUnitOfWorkFactory>();
unitOfWork = _unitOfWorkFactory.Create();
SaveUnitOfWork(unitOfWork);
}
return unitOfWork;
}
}
private static IUnitOfWork GetUnitOfWork()
{
if (HttpContext.Current != null)
{
if (HttpContext.Current.Items.Contains(HTTPCONTEXTKEY))
{
return (IUnitOfWork)HttpContext.Current.Items[HTTPCONTEXTKEY];
}
return null;
}
else
{
Thread thread = Thread.CurrentThread;
if (string.IsNullOrEmpty(thread.Name))
{
thread.Name = Guid.NewGuid().ToString();
return null;
}
else
{
lock (_threads.SyncRoot)
{
return (IUnitOfWork)_threads[Thread.CurrentThread.Name];
}
}
}
}
private static void SaveUnitOfWork(IUnitOfWork unitOfWork)
{
if (HttpContext.Current != null)
{
HttpContext.Current.Items[HTTPCONTEXTKEY] = unitOfWork;
}
else
{
lock (_threads.SyncRoot)
{
_threads[Thread.CurrentThread.Name] = unitOfWork;
}
}
}
}