Joining tables from two databases using entity framework

前端 未结 4 1612
心在旅途
心在旅途 2020-12-17 17:09

I am working on an ASP.NET MVC 4 web application. I am using Entity Framework as the data access layer, using database first approach (.edmx file).

Curr

4条回答
  •  独厮守ぢ
    2020-12-17 17:44

    @CSharper's answer is close. As @Oliver mentioned in the comments, IEnumerable loads the table into application memory, leading to crashes if you have a large database.

    The solution is to use IQueryable, which can be called with LINQ - this produces SQL which is much faster.

    // This is a generic method, modify to your needs
    public ActionResult Details(int? id)
       var one = db.Table1.AsQueryable();
       var two = db2.Table2.AsQueryable(); 
    
       // since you're using MVC EF, I assume you want to put this in a viewmodel 
       // (in this case ObjectCombined)
       // assume "id" is passed as parameter 
       Object1 result1 = (from o in one where one.id == id select o).Single();
       Object2 result2 = (from t in two where t.id == o.id select t).Single();
       ObjectCombined result = new ObjectCombined(result1, result2);
       return View(result);
    }
    

提交回复
热议问题