In my Razor page I would like to use a second DBContext that is connected to a different database.
I have two DBContext that are connecting to two different database that work fine independently in the same app. DB1 is connected to MS Sql Server running on a Linux box, this is the main database. DB2 is connected to MS Sql Server on a Windows Server 2016. I can create CRUD for tables in DB1 and all functions work correctly, I can create Read for a View in DB2 and data is retrieved as expected. When creating a new record in DB1 I would like to merge data from DB2. How do I create/access a DBContext for DB2 in a Razor page CRUD created for a DBContext for DB1. I hope this makes sense. I have tried for the last couple of days googling like crazy and haven't been able to find a solution.
BattlFrog - thank you for you response. It wasn't exactly what I was looking for but it did put me on a better Gooogle Path. How I solved my issue was by the use of "Dependency Injection". I simply added the second DBContext to the contructor of the PageModel. Then in my OnPostAsync() I just had to reference the DBContext. This worked for me, but as I am only learning C#, ASP.Net Core and Razor Pages, this may not be the best approach. Please correct me if I am wrong.
public class IndexModel : PageModel
{
DBContext1 _context1;
DBContext2 _context2;
public IndexModel(DBContext1 context1, DBContext2 context2)
{
_context1 = context1;
_context2 = context2;
}
public async Task<IActionResult> OnPostAsync()
{
IList<ClassName> listName = await _context2.ObjectName.ToListAsync();
// do some stuff here
await _context1.SaveChangesAsync();
}
}