So I’m having a little problem with linq. I want a join to be an OUTER JOIN or an INNER JOIN, depending on whether or not values are filtered on the table
OUTER JOIN:
var query = (from tblA in dc.tblA
join tblB in GetMyTable() on tblA.Ref equals tblB.RefA into joinedTblB
from tblB in joinedTblB.DefaultIfEmpty()
select tblA);
INNER JOIN:
var query = (from tblA in dc.tblA
join tblB in GetMyTable() on tblA.Ref equals tblB.RefA into joinedTblB
from tblB in joinedTblB
select tblA);
What I want is to combine this in the same query, and by checking some condition do either an OUTER JOIN or an INNER JOIN, something like this:
var query = (from tblA in dc.tblA
join tblB in GetMyTable() on tblA.Ref equals tblB.RefA into joinedTblB
from tblNEWB in ((checkCondition==false) ? joinedTblB.DefaultIfEmpty() : joinedTblB)
select new {
tblA.ValueA,
tblNEWB.ValueB
});
I was hoping this would work, but I get an error saying “InvalidOperationException: Member access ‘System.String ValueB’ of ‘tblB’ not legal on type ‘System.Collections.Generic.IEnumerable’1 [tblB]”
Am I missing something here?
UPDATE:
What I want is an outer join, but linq did not produce the query I hoped for, when conditions are set on tlbB. Turning on SQL Profiler gives this query:
LEFT OUTER JOIN tblB ON tblA.Ref = tblB.REfA AND tlbB.Key = '100'
While the correct query should be:
LEFT OUTER JOIN tblB ON tblA.Ref = tblB.RefA
WHERE tblB.Key = '100'
The reason for this is my GetMyTable-function that sets condition to the table in the join.
The first step to getting what you are asking for is to recognize that two distinct sql statements are required. LinqToSql is not going to send your condition into the database so the database can figure out what kind of join should happen based on a value.
The second step, is to switch to the method syntax. This syntax is more composable by conditions.
The third step, is to abandon anonymous types. You have to do unpleasant things to declare the variables you need for query construction with those running around. Just create a type with the properties you need and use that.