C# LINQ to SQL 2 Joins
本文关键字:Joins SQL to LINQ | 更新日期: 2023-09-27 18:06:36
我试图使用LINQ到SQL将3个表连接在一起,但我遇到了一个问题。这是我的代码。
(from table1 in dc.Table1
join table2 in dc.Table2 on table1.Id equals table2.Id
join table3 in dc.Table3 on table2.Id equals table3.Id into merged
from rt in merged.DefaultIfEmpty()
select new { table1.value1, table1.value2, table2.value1, table2.value2, rt.value1, rt.value2 }).ToList();
得到的错误是
The null value cannot be assigned to a member with type System.Double which is a non-nullable value type.
我一开始就不确定我做得对不对。基本上,我想对Table1和Table2进行内部连接然后对table3进行左外连接
你试过了吗?
(from table1 in dc.Table1
join table2 in dc.Table2 on table1.Id equals table2.Id
join table3 in dc.Table3 on table2.Id equals table3.Id into merged
from rt in merged.DefaultIfEmpty()
select new { table1.value1, table1.value2, table2.value1, table2.value2, rt.value1 == null ? 0 : rt.value1, rt.value2 == null ? 0 : rt.value2}).ToList();
重新生成数据库模型
如果你有列在你的db是可空的,他们得到映射到值类型在。net (int
, double
, decimal
等),Linq SQL将生成它们作为可空的类型,所以你不必改变你的Linq SQL语句考虑空,除非这实际上是你的查询的一部分。
try this:
var result = dc.Table1
.Join(dc.Table2, a => a.Id, b => b.Id, (a, b) => new { Id = a.Id, A = a.value1, B = a.value2, C = b.value1, D = b.value2})
.Join(dc.Table3, a => a.Id, b => b.Id, (a, rt) => new { a.A, a.B, a.C, a.D, E = null != rt ? rt.value1 : null, F = null != rt ? rt.value2 : null})
.ToList()