how to connect to two databases in a .NET Core application using Entity Framework Core.

 how to connect to two databases in a .NET Core application using Entity Framework Core?

1. Create DbContext Classes for Each Database

// DbContext for Database 1

public class Database1Context : DbContext

{

    public Database1Context(DbContextOptions<Database1Context> options) : base(options) { }

 

    public DbSet<Product> Products { get; set; }

    public DbSet<Customer> Customers { get; set; }

}

 

// DbContext for Database 2

public class Database2Context : DbContext

{

    public Database2Context(DbContextOptions<Database2Context> options) : base(options) { }

 

    public DbSet<Order> Orders { get; set; }

    public DbSet<Invoice> Invoices { get; set; }

}



2. Configure the DbContexts in Program.cs or Startup.cs

var builder = WebApplication.CreateBuilder(args);

 

// Configure Database 1

builder.Services.AddDbContext<Database1Context>(options =>

    options.UseSqlServer(builder.Configuration.GetConnectionString("Database1Connection")));

 

// Configure Database 2

builder.Services.AddDbContext<Database2Context>(options =>

    options.UseSqlServer(builder.Configuration.GetConnectionString("Database2Connection")));

 

var app = builder.Build();

 

app.MapControllers();

app.Run();



3. Configure Connection Strings in appsettings.json

{

  "ConnectionStrings": {

    "Database1Connection": "Server=server1;Database=db1;User Id=user1;Password=password1;",

    "Database2Connection": "Server=server2;Database=db2;User Id=user2;Password=password2;"

  }

}


4. Using the DbContexts in Controllers or Services

Now, you can inject the DbContext classes into your controllers and use them to query or manipulate data from both databases.

Example Controller:

public class ProductsOrdersController : Controller
{
    private readonly Database1Context _db1Context;
    private readonly Database2Context _db2Context;

    public ProductsOrdersController(Database1Context db1Context, Database2Context db2Context)
    {
        _db1Context = db1Context;
        _db2Context = db2Context;
    }

    public IActionResult Index()
    {
        // Querying Database 1 (Products)
        var products = _db1Context.Products.ToList();

        // Querying Database 2 (Orders)
        var orders = _db2Context.Orders.ToList();

        var viewModel = new ProductsOrdersViewModel
        {
            Products = products,
            Orders = orders
        };

        return View(viewModel);
    }
}



5. Optional: Handling Transactions Across Databases

If you need to perform operations across both databases in a single transaction, you can use TransactionScope to manage a distributed transaction.

Example Using TransactionScope:





public class ProductsOrdersController : Controller
{
    private readonly Database1Context _db1Context;
    private readonly Database2Context _db2Context;

    // Inject both DbContexts

    public ProductsOrdersController(Database1Context db1Context, Database2Context db2Context)

    {

        _db1Context = db1Context;

        _db2Context = db2Context;

    }

 

    public IActionResult Index()

    {

        // Fetching Products from Database 1 (using _db1Context)

        var products = _db1Context.Products.ToList();

 

        // Fetching Orders from Database 2 (using _db2Context)

        var orders = _db2Context.Orders.ToList();

 

        // Combine data if necessary or use them in separate sections on your view

        var viewModel = new ProductsOrdersViewModel

        {

            Products = products,

            Orders = orders

        };

 

        // Pass the combined data to the view

        return View(viewModel);

    }

 

public IActionResult Index2()

{

using (var transaction = new TransactionScope())

{

    // Perform operations on Database 1

    _db1Context.Products.Add(new Product { Name = "New Product" });

    _db1Context.SaveChanges();

 

    // Perform operations on Database 2

    _db2Context.Orders.Add(new Order { ProductId = 1, Quantity = 10 });

    _db2Context.SaveChanges();

 

    // Commit the transaction

    transaction.Complete();

}

       }

 }



Comments

Popular posts from this blog

Multiline to singleline IN C# - CODING

EF Core interview questions for beginners

EF Core interview questions for experienced