LINQ SQL: Left Outer Join on 2 Parameters
I am trying to do a Left Out Join on 2 parameters, but failing miserably.
Basically, what i need is
DEC开发者_如何学运维LARE @SomeValue
SET @SomeValue = 99
SELECT * FROM
[Table1] LEFT OUTER JOIN [Table2]
ON ([Table1].[Field1]=[Table2].[Field1] AND [Table2].[Field2]=@SomeValue)
How can I do this using LINQ?
A second go... Not sure I entirely like this solution - but one approach is:
var someValue = 99;
var preQuery = from t2 in Table2
where t2.Field2 == someValue
select t2;
var query = from t1 in Table1
join t2 in preQuery on t1.Field1 equals t2.Field1
select new
{
T1 = t1,
T2 = t2.FirstOrDefault()
};
LINQ to SQL:
int someValue = 99;
var query =
from table1 from dc.Table1Items
join table2 from dc.Table2Items
on new { table1.Field1, Field2 = someValue } equals new { table2.Field1, table2.Field2 } into table2Items
from table2 in table2Items.DefaultIfEmpty()
select new
{
table1,
table2,
};
var someValue = 99;
var query = from t1 in Table1
join t2 in Table2
on t1.Field1 equals t2.Field1 into tempTable
from t3 in tempTable.Where(v => v.Field2 == someValue).DefaultIfEmpty()
select new { t1, t3};
This is my favorite syntax for left outer joins:
from t1 in Table1
from t2 in Table2
.Where(x => x.Field1 == t1.Field1 &&
x.Field2 == someValue)
.DefaultIfEmpty()
select new { t, t2 }
Assuming you want this in Linq:
var someValue = 99;
var qry = from t1 in Table1
join t2 in Table2 on t1.Field1 equals t2.Field1 into tempTable
from t3 in tempTable.FirstOrDefault()
where (t3==null || t3.Field2 == someValue)
select new
{
T1 = t1,
T2 = t3
};
var query = from t1 in table1 join t2 in table2 equals t2.field2 = @somevalue into new table
from t in table.DefaultIfEmpty() select new { t1, t2== null ? t1.field : t2.field };
精彩评论