Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)

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? The database doesn't allow for nulls in that field, and an int can't be null in .net

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.

like image 831
ECC-Dan Avatar asked Nov 20 '13 15:11

ECC-Dan


2 Answers

Of course it would make the check. Think about how Entity Framework has to construct the query from your LINQ statement. It uses a lot of reflection (as shown in this SO question) to get the job done. 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.

like image 195
Corey Adler Avatar answered Oct 06 '22 07:10

Corey Adler


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.

I am using EF 6.

like image 33
krprasad Avatar answered Oct 06 '22 07:10

krprasad