Search code examples
c#linq-to-entitiesedmx

Is it possible to use two context entities from two different database


Is it possible to use two context entities from two different database

Code connectiong to one entity:

 Using one FoodSupplyEntities
 using (var contextFood = new FoodSupplyEntities())
        {
        var _result = (from _FoodSupplyStatus in contextFood.FoodSupplyStatus
                      join _FoodQualityStatus in contextFood.FoodQualityStatus

But is it possible to join for example another table from a different entities from another server.?

Sample (Dont know but it might gosomething like this.)

  using (var contextFood = new FoodSupplyEntities() and contextKitchenware = new KitchenwareEntities() )
        {
        var _result = (from _FoodSupplyStatus in contextFood.FoodSupplyStatus
                      join _KitchenwareSupplyStatus in contextKitchenware.KitchenwareSupplyStatus

Solution

  • Suppose you have 2 tables in 2 different databases:

    1. User in Database1
    2. Orders in Database2 where UserId of User table in database 1 is referring OrderedBy in Orders table.

    I have Created 2 different context. now i will create 2 queries for 2 different context and will make join on these queries on UserId and OrderedBy like:

    List<OrderDetails> GetOrderDetails()
        {
            var users = this.TestDb1ModelUnit.GetRepository<User_Login>().GetAll();
            var orders = this.TestDb2ModelUnit.GetRepository<OrderDetail>().GetAll();
    
            var orderDetails = users.Join(orders,
                usr => usr.User_Id,
                ord => ord.OrderedBy,
                (usr, ord) => new { usr, ord }
                ).ToList(); 
        }