如何在Repository Pattern中处理两个数据库?

时间:2018-01-19 04:35:56

标签: c# .net entity-framework repository-pattern unit-of-work

我在3个不同的数据库中为数据创建DAL。我的"去"解决方案是EF和Repository / UoW模式。但我从未使用过3个数据库。一些"查询"是跨数据库 - 您必须查询两个数据库才能返回值。

使用一个数据库,我会这样做:

public class UnitOfWork : IUnitOfWork, IDisposable
{
    protected SchoolContext Context { get; }
    public IStudentRepository Student { get; }

    public UnitOfWork(SchoolContext context)
    {
        Context = context;
        Student = new StudentRepository(Context);
    }

    public int Complete()
    {
        return Context.SaveChanges();
    }

    public void Dispose()
    {
        Context?.Dispose();
    }
}

public class StudentRepository : Repository<MoveDto>, IMoveRepository
{
    public StudentRepository(SchoolContext dbContext) 
        : base(dbContext)
    {
    }

    public int GetStudentSomething(int studentId)
    {
        return SchoolContext.Students.Where(m => m.StudentId == studentId);
    }

    private SchoolContext SchoolContext => Context as SchoolContext;
}
但是有两个......我很困惑。我会这样做..但它闻起来:

public class UnitOfWork : IUnitOfWork, IDisposable
{
    protected SchoolContext sContext { get; }
    protected ClubContext cContext { get; }

    public IStudentRepository Student { get; }

    public UnitOfWork(SchoolContext s_context, ClubContext c_context)
    {
        sContext = s_context;
        cContext = c_context;
        Student = new StudentRepository(sContext, cContext);
    }

    public int sComplete()
    {
        return sContext.SaveChanges();
    }

    public int cComplete()
    {
        return cContext.SaveChanges();
    }        

    public int Complete()
    {
        return sComplete() + cComplete();
    }        


    public void Dispose()
    {
        sContext?.Dispose();
        cContext?.Dispose();
    }
}

public class StudentRepository : Repository<MoveDto>, IMoveRepository
{
    public StudentRepository(SchoolContext s_context, ClubContext c_context) 
        : base(s_context, c_context)
    {
    }

    public int GetStudentSomething(int studentId)
    {
        return SchoolContext.Students.Where(m => m.StudentId == studentId);
    }

    private ClubContext ClubContext => cContext as ClubContext;
    private SchoolContext SchoolContext => sContext as SchoolContext;
}
这是好事吗?问题是,您将如何处理两个数据库和存储库模式?谢谢!

0 个答案:

没有答案