通过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

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