左外连接复杂条件

时间:2014-12-15 13:05:40

标签: c# linq entity-framework tsql left-join

如何使用Linq进行这样的SQL查询?

select DISTINC
....
   from Table1
     LEFT OUTER JOIN Table2
     ON Table2.Field1 = Table1.Field1 AND
        Table2.Field2 = Table1.Field2 AND
        Table2.Field3 = Table1.Field3 AND
        (
        ( Table1.Field4 = 'Something' AND ( Table2.Field5 = 'Something'
                                 OR Table2.Field5 = 'Something' ) )
        OR
        ( Table1.Field4 = 'Something' AND ( Table2.Field5 = 'Something'
                                 OR Table2.Field5 = 'Something' ) )
        OR
        ( Table1.Field4 = 'Something' AND ( Table2.Field5 = 'Something'
                                 OR Table2.Field5 = 'Something'
                                 OR Table2.Field5 = 'Something' ) )
        )

   where 
   ....
   order by ...

我一直在LinQ做LEFT OUTER JOINS,但只有这样的等于

from Table1 in ....
  join Table2 in ....
    on new { Table1.Field1, Table1.Field2 }
    equals new { Table2.UNField1V, Table2.Field2 }
    into Join1
  from Name in Join1.DefaultIfEmpty()
  where
  ....
  select new { ... }

但是我不知道在我写过的SQL查询等复杂条件下做类似的事情。

1 个答案:

答案 0 :(得分:1)

from t1 in Table1
from t2 in Table2.Where(t2 => t2.Field1 == t1.Field1 && /* ... complex join condition */)
                 .DefaultIfEmpty()
select new
{
    t1.AnyReferenceField,
    (int?)t2.AnotherInt32Field // !
    /* ... */
}

请不要忘记将t2的值字段转换为可为空。否则,您将获得类似于The cast to value type 'System.Int32' failed because the materialized value is null. Either the result type's generic parameter or the query must use a nullable type.的异常。

如果您想要查询语法:

from t1 in Table1
from t2 in (from t2 in Table2
            where t2.Field1 == t1.Field1 && /* ... complex join condition */
            select t2).DefaultIfEmpty()
select new { /* ... */ }