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

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

问题描述:

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

I am trying to create a .NET core application that connects to multiple databases, but using one generic repository that contains the logic for all CRUD operations. What is the best way to achieve this?

    public Repository(ApplicationDbContext dbContext)
    {
        _dbContext = dbContext;
        _set = _dbContext.Set<T>();
    }

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

Above is the constructor of my repository. Here, I inject the ApplicationDbContext. I am looking for a way to make this ApplicationDbContext generic, so I only have to need only one repository, in which I can inject different contexts for accessing multiple databases. Essentially I am looking for something like this:

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

    }
}

在哪里可以换出 dbContext 并将其替换为连接到另一个数据库的另一个上下文.

Where I can swap out the dbContext and replace it with another context that connects to another Database.

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

You could set two parameters for your repository and add constrains on them, asusume that your dbContext is inherited from 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();
    }
}

ITestReposiroty:

ITestReposiroty:

public interface ITestRepository<TContext,T>
    where TContext : DbContext
    where T : BaseEntity
{       
    List<T> GetAll();
}

Startup.cs

services.AddScoped(typeof(ITestRepository<,>), typeof(TestRepository<,>));

控制器:

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();
    }
}