通过 Entity Framework Core 将多个数据库连接到 .NET core 项目

wse*_*err 4 c# entity-framework-core .net-core asp.net-core

我正在尝试创建一个连接到多个数据库的 .NET Core 应用程序,但使用一个包含所有 CRUD 操作逻辑的通用存储库。实现这一目标的最佳方法是什么?

    public Repository(ApplicationDbContext dbContext)
    {
        _dbContext = dbContext;
        _set = _dbContext.Set<T>();
    }
Run Code Online (Sandbox Code Playgroud)

上面是我的存储库的构造函数。在这里,我注入 ApplicationDbContext。我正在寻找一种使该 ApplicationDbContext 通用的方法,因此我只需要一个存储库,在其中我可以注入不同的上下文来访问多个数据库。本质上我正在寻找这样的东西:

public class Repository_1<T> where T:EntityBase
{
    public Repository_1(IDbContext dbContext)
    {

    }
}
Run Code Online (Sandbox Code Playgroud)

我可以在其中交换 dbContext 并将其替换为连接到另一个数据库的另一个上下文。

Moj*_*ava 8

创建基本上下文并将所有设置包含到 DBSET 中:

public abstract class BaseContext : DbContext
{
    public BaseContext(DbContext options)
    : base(options)
    { }
    public DbSet<object> FirstDbSet { get; set; }
    ...
}
Run Code Online (Sandbox Code Playgroud)

两个 DB(数据库)均继承自 BaseContext:

public class NavaContext : BaseContext
{
    public NavaContext (DbContext<NavaContext> options) : base(options)
    {

    }
}

public class StackContext : BaseContext
{
    public StackContext(DbContext<StackContext> options) : base(options)
    {

    }
}
Run Code Online (Sandbox Code Playgroud)

并在以下位置注册Startup.cs

public IServiceProvider ConfigureServices(IServiceCollection services)
{
    services.AddDbContext<NavaContext>(options => options.UseSqlServer(Configuration.GetConnectionString("LATAMConnectionString")));
    services.AddDbContext<StackContext>(options => options.UseSqlServer(Configuration.GetConnectionString("EUConnectionString")));

    // Autofac
    var builder = new ContainerBuilder();

    // needed only if you plan to inject ICollection<BaseContext>
    builder.RegisterType<NavaContext>().As<BaseContext>();
    builder.RegisterType<StackContext>().As<BaseContext>();

    builder.Populate(services);


    return new AutofacServiceProvider(builder.Build());
}
Run Code Online (Sandbox Code Playgroud)

添加连接字符串appsettings.json

"ConnectionStrings": {
  "NavaConnectionString": "Server=(localdb)\\mssqllocaldb;Database=ContosoUniversity1;Trusted_Connection=True;MultipleActiveResultSets=true",
  "StackConnectionString": "Server=(localdb)\\mssqllocaldb;Database=ContosoUniversity1;Trusted_Connection=True;MultipleActiveResultSets=true"
}
Run Code Online (Sandbox Code Playgroud)

现在你可以注入两个上下文:

public class ReportRepository : IReportRepository
{
    private readonly NavaContext latamDbContext;
    private readonly StackContext euDbContext;

    public ReportRepository(NavaContext latamDbContext, StackContext euDbContext)
    {
        this.latamDbContext = latamDbContext;
        this.euDbContext = euDbContext;
    }
}
Run Code Online (Sandbox Code Playgroud)

或者如果您打算注入collection上下文:

public class ReportRepository : IReportRepository
{
    private readonly ICollection<BaseContext> dbContexts;

    public ReportRepository(ICollection<BaseContext> dbContexts)
    {
        this.dbContexts = dbContexts;
    }
}
Run Code Online (Sandbox Code Playgroud)

访问特定上下文:

var _stackContext= dbContexts.FirstOrDefault(x => x is StackContext) as StackContext;
var _navaContext= dbContexts.FirstOrDefault(x => x is NavaContext) as NavaContext;
Run Code Online (Sandbox Code Playgroud)


Rya*_*yan 5

您可以为存储库设置两个参数并对它们添加约束,假设您的 dbContext 继承自DbContext

public class TestRepository<TContext, T> : ITestRepository<TContext,T> 
    where TContext : DbContext
    where T : BaseEntity
{

    private readonly TContext _context;
    private DbSet<T> entities;


    public TestRepository(TContext context)
    {
        _context = context;
        entities = context.Set<T>();
    }



    public List<T> GetAll()
    {

        return entities.AsNoTracking().ToList();
    }
}
Run Code Online (Sandbox Code Playgroud)

ITestRepository:

public interface ITestRepository<TContext,T>
    where TContext : DbContext
    where T : BaseEntity
{       
    List<T> GetAll();
}
Run Code Online (Sandbox Code Playgroud)

启动.cs

services.AddScoped(typeof(ITestRepository<,>), typeof(TestRepository<,>));
Run Code Online (Sandbox Code Playgroud)

控制器:

public class ProductsController : ControllerBase
{
    private readonly ITestRepository<ApplicationDbContext, Product> _repository;

    public TestRepoController(ITestRepository<ApplicationDbContext, Product> repository)
    {
        _repository = repository;
    }
    // GET api/products

    [HttpGet]
    public List<Product> Get()
    {
        return _repository.GetAll();
    }
}
Run Code Online (Sandbox Code Playgroud)