要在ef core中存储两个不同的数据库,需要创建两个不同的dbcontext。
首先,在appsettings.json文件中
"ConnectionStrings": {
"DefaultConnection": "Connection string of the database where the quest table is located",
"NewConnection": "Connection string of the database where the Heroes table is located" }
public class FirstdbContext : DbContext
{
public FirstdbContext (DbContextOptions<FirstdbContext > options) : base(options)
{
}
public DbSet<Quest> Quest { get; set; }
}
public class SeconddbContext : DbContext
{
public SeconddbContext (DbContextOptions<SeconddbContext > options) : base(options)
{
}
public DbSet<Heroes> Heroes { get; set; }
}
在startup.cs ConfigureServices方法中:
public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews();
services.AddDbContext<FirstdbContext >(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
services.AddDbContext<SeconddbContext >(options =>
options.UseSqlServer(Configuration.GetConnectionString("NewConnection")));
}
[Route("api/[controller]")]
[ApiController]
public class HomeController : ControllerBase
{
private readonly MydbContext _context1;
private readonly TestdbContext _context2;
public HomeController (MydbContext context1, TestdbContext context2)
{
_context1 = context1;
_context2 = context2;
}
[HttpPost]
public async Task<ActionResult<CreateDungeon>> ProcessForm([FromBody]CreateDungeon data)
{
// Read quest data from form and add to DB via EF
_context1.Quest.Add(data.Quest);
try
{
await _context1.SaveChangesAsync();
}
catch (DbUpdateException)
{
if (QuestExists(data.Quest.Id))
{
return Conflict();
}
else
{
throw;
}
}
// Read heroes data from form and add to DB via EF
_context2.Heroes.Add(data.Heroes);
try
{
await _context2.SaveChangesAsync();
}
catch (DbUpdateException)
{
if (HeroesExists(Heroes.Id))
{
return Conflict();
}
else
{
throw;
}
}
return Ok();
}
}