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

.net, c#, entity-framework, entity-framework-6

Solution

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.

Problem

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.

Original source