2013-08-01 11 views
3

我有一个属性是不是 null(这是一个PK)。但我有一个使用LEFT JOIN在表的查询,创建空值Linq查询可能为null属性不是

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; } 

的可能性

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


我念叨LET,也试图与一些值(如0),以填补空值。

如何将空值传递给属性不为null?

回答

3

你可以尝试用默认值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) 
}); 
+0

当我尝试它,我没有尝试使用**''* *去尝试它。 –

+0

这就像一个魅力= D谢谢,并感谢我在SO = P –

2

尝试指定的默认值,你希望它是:(?INT)bLeft.DefaultIfEmpty(0)bLeft.DefaultIfEmpty(-1)

+0

O.O得到最快的重播好吧,我现在很高兴收获。我不知道有可能这样做= X也要测试它=) –

+0

这是一个实体不是一个属性单独=(我需要声明一些像'new TableBClass()' –

+1

这完全取决于你想要什么作为缺省值,如果没有的话 或者只是在你选择的匿名类型中做IdBTemp为空 –