Entity Framework Linq equals value or is null

为君一笑 提交于 2020-01-15 05:53:07

问题


I am trying with linq to get a list of items from a view where the field LocationId is either a value or is null. The field LocationId is int?.

The code which i am trying is something like this:

var items = _context.Items.Where(
    d => d.LocationId == null || d.LocationId == query.Location).ToList();

Unfortunately, as seen with SqlProfiler the generated sql does not include d.LocationId == null.

What is different from the possible duplicate question is that there where only checking for a value is null. What i want is somewhere in the line of SELECT * FROM Items WHERE LocationId = @some_param OR LocationId IS NULL.

Edit: After the comments with the mapping not being right I have found the issue. The mapping was something like

HasKey(x => new { x.EquipmentId, x.LocationId});

Because it all comes from a view. Seems like if LINQ sees a property as part of a key it will assume it is non-nullable, does not matter if the property is nullable (int?)


回答1:


The mapping was wrong. Removed LocationId from the HasKey mapping.

Seems like if LINQ sees a property as part of a key it will assume it is non-nullable, does not matter if the property is nullable (int?)



来源:https://stackoverflow.com/questions/38762604/entity-framework-linq-equals-value-or-is-null

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!