(Linq / Lambda)使用2个DBContext连接2个或更多表

时间:2015-05-14 11:16:11

标签: c# linq entity-framework lambda

我得到这样的错误:指定的LINQ表达式包含对与不同上下文关联的查询的引用。

var employee = new ApplicationDbContext().Employee;
var otherTable = new OtherDbContext().OtherTable;

var returnValue = (from e in employee
                        join o in otherTable on e.Id equals o.Id
                        select new
                        {
                            e.Name,
                            e.Address,
                            o.Others
                        });

任何解决方案? 谢谢!

2 个答案:

答案 0 :(得分:2)

您应该通常实例化您的DBContext,而不是指定表/模型。 例如:

 private ApplicationDBContext db = new ApplicationDbContext();

然后选择您是否还要使用LINQ或Raw SQL。我相信你对SQL更熟悉,因为你提到加入表,为什么不使用它呢? Here's a tutorial on how to use Raw SQL.

If you still insist in using LINQ and involve join, here's a good reference for it.

答案 1 :(得分:0)

List<Employee> empList = new ApplicationDbContext().Employee.ToList();
List<OtherTable> othrList= new OtherDbContext().OtherTable.ToList();

var returnValue = (from e in empList 
                        join o in othrList on e.Id equals o.Id
                        select new
                        {
                            e.Name,
                            e.Address,
                            o.Others
                        });

试试这个会起作用.....