在单个webapi控制器中使用多个数据库

时间:2018-10-12 14:44:43

标签: c# entity-framework asp.net-core

我有一个带有EntityFramework(2.1)的dotnet核心(2.1)webapi项目

我有一个IProjectRepository界面:

public interface IProjectRepository
{
    void GetProject(Guid id);
    void DeleteProject(Guid id);
    Project CreateProject(Project prj);
    int SaveChanges();
}

我也在ProjectRepository类中实现了它:

public class ProjectRepository : IProjectRepository
{
    private readonly ProjectContext context;

    public ProjectRepository(ProjectContext context)
    {
        this.context = context;
    }

    public Project GetProject(Guid id)
    {
        return context.Projects.Find( id );
    }

    public void DeleteProject(Guid id)
    {
        context.Projects.Remove( project );
    }

    public void CreateProject(Project prj)
    {
        context.Projects.Add(project);
    }

    public int SaveChanges()
    {
        return context.SaveChanges();
    }
}

我还有一个ProjectsController

[Route( "api/[controller]" )]
[ApiController]
public class ProjectsController : ControllerBase
{
    private readonly IProjectRepository projectRepository;

    public ProjectsController(IProjectRepository projectRepository)
    {
        this.projectRepository = projectRepository;
    }

    [HttpGet( "{id}", Name = "GetProject" )]
    public ActionResult<Project> GetProjectById( Guid id )
    {
        Project project = projectRepository.GetProject( id );

        if ( project == null )
        {
            return NotFound();
        }
        return project;
    }

    [HttpDelete( "{id}" )]
    public IActionResult DeleteProject( Guid id )
    {
        Project project = projectRepository.GetProject( id );

        if ( project == null )
        {
            return NotFound();
        }

        projectRepository.RemoveProject( project );
        projectRepository.SaveChanges();
        return NoContent();
    }

    /* etc. */
}

我正在Startup.cs-ConfigureServices函数中配置存储库:

services.AddDbContext<ProjectContext>( opt => opt.UseSqlite( "Data Source=" + projectsPath + "\\Projects.db" ) );
services.AddScoped<IProjectRepository, ProjectRepository>();

我想要实现的是在单个控制器内使用不同的数据库,并且还使用单个Model。因此,假设我的HttpPost中有两个不同的ProjectController-请求:

[HttpPost("{id}/foo")]

[HttpPost("{id}/bar")]

对于foo,我想写给foo.db;对于bar,我想写给bar.db。仅向services.AddDbContext<ProjectContext>添加多个呼叫显然是行不通的。 什么是达到我的目标的好方法?

1 个答案:

答案 0 :(得分:6)

  

仅将多个调用添加到服务。AddDbContext显然不起作用。

如果您使用继承并对子类调用AddDbContext,则该方法将起作用。

定义另外两个从ProjectContext继承的上下文。

public class FooContext : ProjectContext {}

public class BarContext : ProjectContext {}

然后使用不同的连接字符串注册它们。

services.AddDbContext<FooContext>(opt => opt.UseSqlite("..."))

services.AddDbContext<BarContext>(opt => opt.UseSqlite("..."))