gpt4 book ai didi

c# - LINQ 中具有外连接的 Nullable Int

转载 作者:行者123 更新时间:2023-11-30 16:51:00 25 4
gpt4 key购买 nike

我有以下 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。但是由于左外连接,它来自数据库的 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 可能为 null - 但如果 pc 为 null,则 pc.CategoryId 逻辑上只会抛出异常。 (如评论中所述,由于查询被翻译成 SQL,它实际上可能不会这样做。但我尝试编写 LINQ 代码,它逻辑上是正确的,并且碰巧可以工作:)

不要忘记 DefaultIfEmpty() 返回一个序列,该序列要么是元素的原始序列,要么是具有一个元素的序列,该元素是元素类型的默认值。如果该元素类型是一个类(我希望它在这里),则默认值为 null,这就是为什么如果没有匹配项,pc 将为 null。

这听起来像你想要的:

Selected = pc != null

关于c# - LINQ 中具有外连接的 Nullable Int,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34231276/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com