Reputation: 384
I want to rewrite this simple MS SQL Query in Linq To SQL:
SELECT * FROM Table1 T1
LEFT JOIN Table2 T2 ON T1.ID = T2.Table1ID OR T1.FirstName = T2.FirstName
How do I rewrite this in Linq To SQL?
Upvotes: 0
Views: 172
Reputation: 152626
Try this, although I don't know how well Linq-to-SQL will translate it:
from t1 in ctx.Table1
from t2 in ctx.Table2
.Where(t => t1.ID == t.Table1ID ||
t1.FirstName == t.Firstname)
.DefaultIfEmpty()
select new {t1, t2}
Upvotes: 3
Reputation: 959
This is an inner join.
from t1 in ctx.Table1
from t2 in ctx.Table2
where t1.ID == t2.Table1ID ||
t1.FirstName == t2.Firstname
select t1
To get a left join it looks like you use DefaultIfEmpty()
, per MSDN.
from t1 in ctx.Table1
from t2 in ctx.Table2.DefaultIfEmpty()
where t1.ID == t2.Table1ID ||
t1.FirstName == t2.Firstname
select t1
Upvotes: 0
Reputation: 15237
I don't believe this can be done because I don't think you can do the OR part of the join. The way you do joins in L2S would be (roughly)
join .. on
new {
T1.ID,
T1.FirstName
} equals new {
T2.Table1ID,
T2.FirstName
}
but that would match both.
Only thing I can think you could do would be to do some sort of subquery in there. But that's probably not what you're looking for. Sklivvz's suggestion may be the best one.
Upvotes: 0