简体   繁体   English

C#LINQ to SQL 2联接

[英]C# LINQ to SQL 2 Joins

I am trying to join 3 tables together using LINQ to SQL but I am running into an issue. 我正在尝试使用LINQ to SQL将3个表连接在一起,但是遇到了问题。 Here is my code. 这是我的代码。

(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 error I'm getting is 我得到的错误是

The null value cannot be assigned to a member with type System.Double which is a non-nullable value type.

I'm not sure I'm doing it correctly in the first place. 我不确定我一开始的做法是否正确。 Basically I want to do an inner join on Table1 and Table2 then a left outer join on that with Table 3. 基本上,我想在Table1和Table2上进行内部联接,然后在表3上进行内部联接。

Did you try this? 你有尝试过吗?

(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();

Regenerate your DB model. 重新生成您的数据库模型。

If you have columns in your db that are nullable and they get mapped to value types in .net ( int , double , decimal , etc), Linq to SQL will generate them as nullable types, so you won't have to change your linq to sql statements to take the null into account, unless that is actually part of your query. 如果您的数据库中有可为空的列,并且它们被映射为.net中的值类型( intdoubledecimal等),Linq to SQL会将它们生成为可为空的类型,因此您不必更改linq sql语句以将null纳入考虑范围,除非这实际上是查询的一部分。

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()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM