简体   繁体   English

为什么实体框架在WHERE子句中添加不必要的(AND [param] IS NOT NULL)?

[英]Why does Entity Framework add unnecessary (AND [param] IS NOT NULL) in WHERE clause?

Given this simple model: 给定这个简单的模型:

public partial class UserColumnGrid
    {
        public int UserColumnGridID { get; set; }
        public int UserID { get; set; }
        public int ColumnGridID { get; set; }
        public int ColumnWidth { get; set; }
        public bool IsVisible { get; set; }

        public virtual ColumnGrid ColumnGrid { get; set; }
        public virtual User User { get; set; }
    }

And this simple query: (userID is an int) 这个简单的查询: (userID是一个i​​nt)

dbContext.UserColumnGrid.Where(ucg => ucg.UserID == userID).ToList();

The following query is generated: 生成以下查询:

SELECT [Extent1].[UserColumnGridID]  AS [UserColumnGridID],
       [Extent1].[UserID]            AS [UserID],
       [Extent1].[ColumnGridID]      AS [ColumnGridID],
       [Extent1].[ColumnWidth]       AS [ColumnWidth],
       [Extent1].[IsVisible]         AS [IsVisible]
FROM   [dbo].[UserColumnGrid] AS [Extent1]
WHERE  ([Extent1].[UserID] = 1 /* @p__linq__0 */)
       AND (1 /* @p__linq__0 */ IS NOT NULL)

Why is this AND NOT NULL criterion added? 为什么要添加AND AND NULL准则? The database doesn't allow for nulls in that field, and an int can't be null in .net 数据库不允许该字段为null,.net中的int不能为null

This happens all over my queries. 这在我的所有查询中都会发生。 It's pretty annoying, but is it impacting performance? 这很烦人,但是会影响性能吗?

How can I get rid of it? 我该如何摆脱呢?

This is on a database-first model. 这是基于数据库的模型。

Of course it would make the check. 当然,它将进行检查。 Think about how Entity Framework has to construct the query from your LINQ statement. 考虑一下实体框架如何从LINQ语句构造查询。 It uses a lot of reflection (as shown in this SO question ) to get the job done. 它需要大量的反思(如本SO问题所示)来完成工作。 As such, using reflection means that it's probably not spending the time thinking about what type a specific field is, or if it's nullable or not--especially since it could just add that null check and be done with the query. 因此,使用反射意味着它可能不会花时间思考特定字段的类型,或者该字段是否可为空-尤其是因为它可以添加该空值检查并通过查询来完成。

My guess is that that was done on purpose since using reflection to grab the type and then to see if it is or isn't nullable could possibly be a major performance hit--especially for any really complicated query (like one with a lot of parameters). 我的猜测是故意这样做的,因为使用反射来获取类型,然后查看它是否可为空可能是对性能的重大打击-特别是对于任何非常复杂的查询(例如具有很多查询的查询)参数)。 It might not be necessary, but I think it makes things a lot simpler for everyday use. 可能没有必要,但是我认为这使日常使用变得简单得多。

I got rid of the extra "(AND [param] IS NOT NULL) in WHERE clause" by marking the property in the model class required using data annotation. 通过使用数据注释在所需的模型类中标记属性,我摆脱了多余的“(WHERE子句中的AND(参数)不是空)”。

I am using EF 6. 我正在使用EF 6。

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

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