如何将多个数据库添加到UnitOfWork,通用存储库和Entity Framework模式

时间:2019-05-25 07:14:20

标签: c# entity-framework design-patterns repository-pattern unit-of-work

我有一个Windows Forms应用程序和通用的Entity Framework(最新版本)方法以及多层设计模式。

我正在编写此代码。加载第一个数据库是好的,但不能加载第二个数据库 并显示此错误:无效的对象名称'dbo.Section'。但存在'dbo.section'

存储层:

private readonly DbSet<T> dbSetGlobalERP;
    private readonly DbSet<T> dbSetHamkaranSystem;        
    private T Entity;
    private IEnumerable<T> Entities;

public Repository(GlobalERPEntities dbcontextGlobalERP, HamkaranSystemEntities dbcontextHamkaranSystem)
{
    base.dbContextGlobalERP = dbcontextGlobalERP;
    dbSetGlobalERP = base.dbContextGlobalERP.Set<T>();

    base.dbContextHamkaranSystem = dbcontextHamkaranSystem;
    dbSetHamkaranSystem = base.dbContextHamkaranSystem.Set<T>();
}

   public virtual IEnumerable<T> GetAll()
    {
        return dbSetGlobalERP.ToList();
    }

    public virtual IEnumerable<T> GetAll2()
    {
        return dbSetHamkaranSystem.ToList();//error
    }

UnitOfWork层:调用从存储库层获取所有方法

public UnitOfWork(GlobalERPEntities dbContextGlobalERP, HamkaranSystemEntities dbContextHamkaranSystem)
{
    base.dbContextGlobalERP = dbContextGlobalERP;
    base.dbContextHamkaranSystem = dbContextHamkaranSystem;
}       

public IRepository<T> Repository<T>() where T : class
{
    if (repositories == null)
    {
        repositories = new Dictionary<Type, object>();
    }

    if (repositories.Keys.Contains(typeof(T)) == true)
    {
        return repositories[typeof(T)] as Repository<T>;
    }
    Repository<T> repo = new Repository<T>(dbContextGlobalERP, dbContextHamkaranSystem);
    repositories.Add(typeof(T), repo);
    return repo;
}

 public bool SaveChanges()
    {
        bool returnValue = true;
        using (var dbContextTransaction = dbContextGlobalERP.Database.BeginTransaction())
        {
            try
            {
                dbContextGlobalERP.SaveChanges();
                dbContextTransaction.Commit();
            }
            catch (Exception)
            {
                returnValue = false;
                dbContextTransaction.Rollback();
            }
        }
        return returnValue;
    }

BLL层:调用从UnitOfWork层获取所有方法

private readonly IUnitOfWork unitOfWork;
public static List<HRPersonView> personFullName = new List<HRPersonView>();

public Service_HR_Person(IUnitOfWork unitOfWork)
{
    this.unitOfWork = unitOfWork;
    FillList();
}

public virtual IEnumerable<HRPerson> GetAll()
{
    return unitOfWork.Repository<HRPerson>().GetAll().ToList();
}

public virtual IEnumerable<Section> GetAll2()
{
    return unitOfWork.Repository<Section>().GetAll2().ToList();
}

UI层:

 var AllList = service.GetAll2();
            dgvList.DataSource = (from sec in AllList
                                  select new
                                  {
                                      sec.ID,
                                      sec.Section,
                                  }).ToList();

如何向该模式添加多数据库?

0 个答案:

没有答案