LINQ 中具有外连接的 Nullable Int
Nullable Int in LINQ with outer join
我有以下 LINQ 查询
var categories = (from c in context.Categories
join pc in context.ProductCategories
on new { Id = c.CategoryId, ProductId = 12 }
equals new { Id = pc.CategoryId, ProductId = pc.ProductId }
into productCategories
from pc in productCategories.DefaultIfEmpty()
select new ViewModel
{
CategoryId = c.CategoryId,
Category = c.Name,
Selected = (pc.CategoryId == null) ? false : true
}).ToList();
这在 pc.CategoryId == null
处给了我一个编译器警告,说它将始终为 false,因为 CategoryId
是 Int 类型且不可空。但是由于左外连接,它来自数据库 null
。
如果我忽略警告,一切都会按预期进行。这样可以吗,或者有更好的方法吗?
This gives me a compiler warning at pc.CategoryId == null saying it will always be false as CategoryId is not nullable. But because of left outer join it comes as null from database.
不,pc
可能为空 - 但如果 pc
为空,pc.CategoryId
逻辑上只会抛出异常。 (如评论中所述,由于查询被翻译成 SQL,它实际上可能不会这样做。但我尝试编写 LINQ 代码,它 逻辑上 正确并且碰巧工作:)
不要忘记 DefaultIfEmpty()
returns 一个序列,它可以是元素的原始序列,也可以是具有一个元素的序列,该元素是元素类型的默认值。如果该元素类型是 class(我希望它在这里),则默认值为 null
,这就是如果没有匹配项,pc
将为 null 的原因。
听起来你想要:
Selected = pc != null
我有以下 LINQ 查询
var categories = (from c in context.Categories
join pc in context.ProductCategories
on new { Id = c.CategoryId, ProductId = 12 }
equals new { Id = pc.CategoryId, ProductId = pc.ProductId }
into productCategories
from pc in productCategories.DefaultIfEmpty()
select new ViewModel
{
CategoryId = c.CategoryId,
Category = c.Name,
Selected = (pc.CategoryId == null) ? false : true
}).ToList();
这在 pc.CategoryId == null
处给了我一个编译器警告,说它将始终为 false,因为 CategoryId
是 Int 类型且不可空。但是由于左外连接,它来自数据库 null
。
如果我忽略警告,一切都会按预期进行。这样可以吗,或者有更好的方法吗?
This gives me a compiler warning at pc.CategoryId == null saying it will always be false as CategoryId is not nullable. But because of left outer join it comes as null from database.
不,pc
可能为空 - 但如果 pc
为空,pc.CategoryId
逻辑上只会抛出异常。 (如评论中所述,由于查询被翻译成 SQL,它实际上可能不会这样做。但我尝试编写 LINQ 代码,它 逻辑上 正确并且碰巧工作:)
不要忘记 DefaultIfEmpty()
returns 一个序列,它可以是元素的原始序列,也可以是具有一个元素的序列,该元素是元素类型的默认值。如果该元素类型是 class(我希望它在这里),则默认值为 null
,这就是如果没有匹配项,pc
将为 null 的原因。
听起来你想要:
Selected = pc != null