实体框架使多个表失败 [英] Entity Framework left join multiple tables failure

查看:308
本文介绍了实体框架使多个表失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Entity Framework 6,我有几个实体和一个查询,如下所示:

I'm using Entity Framework 6 and I have few entities and a query like the following:

var results = (from e1 in dataContext.Entity1
                   .Where(x => x.Key1 == 1)
               from e2 in dataContext.Entity2
                   .Where(x => x.Key2 == e1.Key1)
                   .DefaultIfEmpty()
               from e3 in dataContext.Entity3
                   .Where(x => x.Key3 == e1.Key1 || x.Key3 == e2.Key2)
                   .DefaultIfEmpty()
               select new 
               {
                   E1 = e1,
                   E2 = e2,
                   E3 = e3
               }).ToList();

由于连接到Entity2和Entity3是连接,e2或e3可能为null。我发现如果e2为空,则使用消息非静态方法需要目标抛出异常System.Reflection.TargetException。如果我将连接更改为Entity3,我仍然有相同的错误。

Since the joins to Entity2 and Entity3 are left joins, e2 or e3 may be null. I found out if e2 is null, exception System.Reflection.TargetException is thrown with message "Non-static method requires a target". And if I change the join to Entity3 as the following, I still got the same error.

from e3 in dataContext.Entity3
               .Where(x => x.Key3 == e1.Key1 
                      || (e2 != null && x.Key3 == e2.Key2))
               .DefaultIfEmpty()

如何更改查询?

推荐答案

谢谢各位的建议。最后我想出了这个问题。

Thank you all the suggestions. Finally I figured out the problem.

为了简化问题,我没有告诉Entity1实际上是从存储过程返回的。我认为这是一个表,因为存储过程从表中返回整个记录。原来有人改变了实体框架的存储过程的包装器来返回Entity1列表。之后,我将其从EF更改为原始生成的代码,可以正常工作。

To simplify the question, I didn't tell the Entity1 is actually the return from a stored procedure. I thought it is the same as a table since the stored procedure returns the whole records from the table. It turns out somebody changed the Entity Framework's wrapper of the stored procedure to return the Entity1 list. After I changed it back to the originally generated code from EF, it works fine.

这篇关于实体框架使多个表失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆