我想在我的ASP.NET MVC 5應用程序,ASPIdentity的One DbContext和My APP的其他數據庫中添加兩個DbContext。我正在使用存儲庫模式。 問題是,如何在BaseRepository中指定每個DbContext的實體? 這是我做的。如何使用UnitOfWork&DatabaseFactory&Generic Repository添加多個DbContext
1- DatabaseFactory & IDatabaseFactory
public class DatabaseFactory<T> where T : DbContext,new()
{
private T dbContext;
public T Init()
{
return dbContext ?? (dbContext = new T());
}
}
public interface IDatabaseFactory<T> where T : DbContext
{
T Init();
}
2- IUnitOfWork &的UnitOfWork
public class UnitOfWork<T> : IUnitOfWork<T> where T : DbContext
{
private readonly IDatabaseFactory<T> dbFactory;
private T dbContext;
public UnitOfWork(IDatabaseFactory<T> dbFactory)
{
this.dbFactory = dbFactory;
}
protected T DbContext
{
get { return dbContext ?? (dbContext = dbFactory.Init()); }
}
public void Commit()
{
DbContext.SaveChanges();
}
}
public interface IUnitOfWork<T> where T : DbContext, IDisposable
{
void Commit();
}
3- BaseRepository.cs
public abstract class BaseRepository<T> where T : class
{
#region Properties
private DbContext dataContext;
private readonly IDbSet<T> dbSet;
protected IDatabaseFactory DbFactory
{
get;
private set;
}
protected DbContext dbContext
{
get { return dataContext ?? (dataContext = DbFactory.Init()); }
}
#endregion
protected BaseRepository(IDatabaseFactory dbFactory)
{
this.DbFactory = dbFactory;
this.dbSet = this.DbContext.Set<T>();
}
#region Implementation
public virtual void Add(T entity)
{
dbSet.Add(entity);
}
public virtual void Update(T entity)
{
dbSet.Attach(entity);
dataContext.Entry(entity).State = EntityState.Modified;
}
public virtual void Delete(T entity)
{
dbSet.Remove(entity);
}
public virtual void Delete(Expression<Func<T, bool>> where)
{
IEnumerable<T> objects = dbSet.Where<T>(where).AsEnumerable();
foreach (T obj in objects)
dbSet.Remove(obj);
}
public virtual T GetById(int id)
{
return dbSet.Find(id);
}
public virtual IEnumerable<T> GetAll()
{
return dbSet.ToList();
}
public virtual IEnumerable<T> GetMany(Expression<Func<T, bool>> where)
{
return dbSet.Where(where).ToList();
}
public T Get(Expression<Func<T, bool>> where)
{
return dbSet.Where(where).FirstOrDefault<T>();
}
#endregion
}
實體框架'DbContext'類已經使用「工作單元」和「庫」模式了。絕對沒有必要將它包裝在另一組中。如果你正確使用它們,你已經免費獲得這個。 –