Linq查询可能为null,而属性不是

本文关键字:属性 null 查询 Linq | 更新日期: 2023-09-27 18:25:52

我有一个属性是NOTnull(它是PK)。但我有一个查询,它在该表中使用了LEFT JOIN,从而创建了空值的可能性

LINQ

(from a in dbContext.TableA
join b in dbContext.TableB on a.IdB equals b.IdB into bLeft
from bTbl in bLeft.DefaultIfEmpty()
select new
{
    IdBTemp = bTbl.IdB, // This value may be null
    IdATemp = a.IdA
}.AsEnumerable().Select(row => new DynamicClassModel()
{
    // Stuff here (convertion to string, concatanations and other stuff)
});

*类别模型*

[Key, DatabaseGenerated(DatabaseGeneratedOption.None)]
[Column("IdB")]
public long IdB { get; set; }

这只是一个小的查询示例。我的查询比这个大,有更多的左联接,还有更多的字段未映射为null,但在这个查询中它们可能是null


我读到了关于LET的文章,还试图用一些值(比如0)填充空值。

如何将null值传递到非null的属性中

Linq查询可能为null,而属性不是

您可以尝试用默认值0:填充它

(from a in dbContext.TableA
join b in dbContext.TableB on a.IdB equals b.IdB into bLeft
from bTbl in bLeft.DefaultIfEmpty()
select new
{
    IdBTemp = bTbl == null ? 0 : bTbl.IdB,
    IdATemp = a.IdA
}.AsEnumerable().Select(row => new DynamicClassModel()
{
    // Stuff here (convertion to string, concatanations and other stuff)
});

但也许您想使用int?。在这种情况下,使用这个:

(from a in dbContext.TableA
join b in dbContext.TableB on a.IdB equals b.IdB into bLeft
from bTbl in bLeft.DefaultIfEmpty()
select new
{
    IdBTemp = bTbl == null ? (int?)null : bTbl.IdB,
    IdATemp = a.IdA
}.AsEnumerable().Select(row => new DynamicClassModel()
{
    // Stuff here (convertion to string, concatanations and other stuff)
});

尝试指定您想要的默认值:bLeft.DefaultIfEmpty(0)bLeft.DefaultIfEmpty(-1)