问题
I am new to EF and trying to do a small project with it. I added a condition to EF but I am having a problem.
My condition is all about IN condition like SQL,
SELECT * FROM table1 WHERE col1 IN (1,2,3...)
Here is my EF....
var res3 = res2.Where(l => !slitDetail
.Any(s => s.BlockId == l.Id
&& s.WarehouseDepot.WarehouseDepotName != "Ara Ürün Depo"
&& s.WarehouseDepot.WarehouseDepotName != "Özel Kesim Depo"));
s.WarehouseDepot might be NULL sometimes which is normal, but if it is null, this query throws an exception.
How can I check if s.WarehouseDepot is null and make it work even if it is null?
回答1:
There are 2 possiblities if s.WarehouseDepot == null
1) You want your Any to return true, in that case you could use something like
var res3 = res2.Where(l => !slitDetail
.Any(s => s.BlockId == l.Id
&& s.WarehouseDepot != null
? (s.WarehouseDepot.WarehouseDepotName != "Ara Ürün Depo" && s.WarehouseDepot.WarehouseDepotName != "Özel Kesim Depo")
: true));
This would use the s.WarehouseDepot only if it has a value otherwise it would return true
2) You want your Any to return false. In this case you could simply replace the true by false in the above expression or use something like
var res3 = res2.Where(l => !slitDetail
.Any(s => s.BlockId == l.Id
&& s.WarehouseDepot != null
&& s.WarehouseDepot.WarehouseDepotName != "Ara Ürün Depo"
&& s.WarehouseDepot.WarehouseDepotName != "Özel Kesim Depo"));
Note that both these outcomes will automatically consider the s.BlockId == l.Id condition too.
来源:https://stackoverflow.com/questions/36883787/how-to-check-if-object-is-null-in-ef