简体   繁体   English

为什么实体框架在从视图中进行选择时会创建子查询?

[英]Why does entity framework create a subquery when selecting from a view?

I have a table called PersonTable with the columns: PersonId, RestarauntId, Age 我有一个名为PersonTable的表PersonId, RestarauntId, AgePersonId, RestarauntId, Age

I have a view called PersonView that does: 我有一个名为PersonView的视图:

select PersonId, 
       RestarauntId, 
       RestarauntName(RestarauntId) as `RestarauntName`, 
       Age 
FROM PersonTable

When I do something as simple as: 当我做一些简单的事情:

var persons = context.PersonView.Where(x=>x.PersonId == 1)
                                .Select(x=> 
                                   new {x.PersonId, 
                                        x.RestarauntId, 
                                        x.RestarauntName, 
                                        x.Age });

The above returns 1 record and I would expect the MySql query to be: 上面返回1条记录,我希望MySql查询是:

SELECT PersonId, RestarauntId, RestarauntName, Age 
FROM PersonView
WHERE PersonId = 1

BUT instead, it generates the following: 但相反,它会生成以下内容:

SELECT 1 AS `C1`, T.PersonId, T.RestarauntId, T.RestarauntName, T.Age
FROM
(SELECT PersonId, RestarauntId, RestarauntName, Age 
FROM PersonView) AS T
WHERE T.PersonId = 1

So it does not matter what I pass to the where clause, it always will get all the records first in a sub-select. 所以我传递给where子句并不重要,它始终会在子选择中首先获得所有记录。 This only happens when I query against the view which I need to, but I was curious as to why it creates the above query instead of the one I expect it to make? 这只发生在我查询我需要的视图时,但我很好奇为什么它创建上述查询而不是我期望它的那个? Is this an Entity Framework issue or a MySql Issue? 这是实体框架问题还是MySql问题?

MySql View does not allow dynamic filters in the query used. MySql View不允许在使用的查询中使用动态过滤器。
There are few hacks used to achieve this. 用于实现此目的的黑客很少。 But by design, mysql views are not dynamic in nature. 但是按照设计,mysql视图本质上不是动态的。 Views always execute the actual query supplied and only on that result, further filtering can be done, as you mentioned in your example. 视图总是执行提供的实际查询,并且只对该结果执行,可以进行进一步的过滤,如您在示例中所述。 For more details, visit Here 有关详细信息,请访问此处

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM