Reputation: 326
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?)
Upvotes: 2
Views: 4204
Reputation: 326
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?)
Upvotes: 1