How to use the let statement in outer join of LINQ to SQL?
Something like below,
from a in tableA
from b in tableB.where(o => a.Key == o.Key).DefaultIfEmpty() //outer join
let x = b.objectBB
where b != null && x != null && x.FilterCode == "X"
So,
Does the above query is fine?
Will the 'let' fail if 'b' is null ?
what will happen with the where clause on 'x'? Does this filter work fine?
Any better way to achieve this also much welcome.!
Seems to me that if you want both sides to be not null, don't you just want an inner join?
from a in tableA
join b in tableB on a.Key equals o.Key
where b.FilterCode == "X"
Related
I want to do a JOIN with LINQ using an OR statement.
Here is the SQL query I'm starting with:
SELECT t.id
FROM Teams t
INNER JOIN Games g
ON (g.homeTeamId = t.id OR g.awayTeamId = t.id)
AND g.winningTeamId != 0
AND g.year = #year
GROUP BY t.id
I'm having trouble converting that ON clause to LINQ. This is where I'm at:
var y = from t in db.Teams
join g in db.Games on t.ID equals g.AwayTeamID //missing HomeTeamID join
where g.WinningTeamID != 0
&& g.Year == year
group t by t.ID into grouping
select grouping;
I think I could use:
join g in db.Games on 1 equals 1
where (t.ID == g.HomeTeamID || t.ID == g.AwayTeamID)
and this works but seems kind of seems hacky. Is there a better way?
I struggled with this as well until I found the following solution, which worked well for my situation:
var y = from t in db.Teams
from g in db.Games
where
(
t.ID == g.AwayTeamID
|| t.ID == g.HomeTeamID
)
&& g.WinningTeamID != 0
&& g.Year == year
group t by t.ID into grouping
select grouping;
Under the covers, your solution probably works very close to this one. However, I bet this one is just a bit faster if you benchmark it since it is not JOINING every item in the first dataset with every item in the second dataset, which could be a disaster if either (or both) dataset were really big.
The where clause applies a boolean condition, so using "||" is the way to go. You can chain multiple where clauses but I believe that will give you a "and" operation, rather than an "or".
I think you can do like this:
from t1 in db.Table1
// inner join with OR condition
from t2 in db.Table2 where t1.col1 == t2.col1 || t1.col2 == t2.col2
// normal inner join
join t3 in db.Table3 on t1.col1 equals t3.col1
// inner join with complex condition
join t4 in db.Table4 on t2.col4 equals t4.col4 where t2.col5.Contains(t4.col5)
// left join with OR condition
from t5 in db.Table5.Where(x => x.col5 == t1.col5 || x.col6 == t1.col6).DefaultIfEmpty()
select new {
x = 1 // select whatever you want here
}
The underlying SQL query probably won't use native sql joins but the above is just a way to make your code look pretty and organized.
this is a bit confusing for me. I know that left outer joins aren't built in to LINQ natively and that you have to use 'into' and 'DefaultIfEmpty()', but I have a bit of a complex SQL query.
The query:
SELECT * FROM TableA as a
LEFT OUTER JOIN TableB as b
on a.ID = b.ID and a.StatusOne = 1 AND b.StatusOne = 1 AND (a.StatusTwo != 1 OR b.StatusTwo!= 1)
LEFT OUTER JOIN TableC as c
on a.ID = c.ID AND a.StatusOne = 1 AND c.StatusOne = 1 AND (a.StatusTwo != 1 OR c.StatusTwo != 1)
WHERE
a.ID = 99999 AND (b.ID is not null OR c.ID is not null)
I'm not even really sure where to begin on this. If someone could help me out I would appreciate it immensely.
I am giving you the idea behind, I didn't tested the code, but to join two tables based on different fields, your join should have a anonymous type to compare.
var one = 1
from a in tableA
join b in tableB on new { a.ID, b.StatusOne } equals new { b.ID, one} into ab
But in your case you have more than one condition, so before calling DefaultIsEmpty, you should check the latest condition
from a in tableA
join b in tableB on new { a.ID, b.StatusOne } equals new { b.ID, one} into ab
from ab in ab.Where(x => x.a.StatusTwo != 1 || x.b.StatusTwo != one).DefaultIfEmpty()
Then the other outer join follows the same pattern and you need to make a final join. A good way to start is downloading the LinqPad and see which lambda expression it generates for your query, and you can take it from there. You can optimize it later but you will get the idea behind the generation. Hope this helps
I am trying to figure out the LINQ syntax for multiple left join, but I am getting the error: The name 'c' is not in scope on the left side of 'equals'. Consider swapping the expressions on either side of 'equals'.
I have already tried swapping, and if I do, it makes both 'c' and 'd' have the "not in scope" error.
var result =
from a in db.tableA
join b in db.tableB //first join (inner join)
on a.field1 equals b.field1
join c in db.tableC //second join (left join)
on a.field1 equals c.field1
into left_one
join d in db.tableD //third join (left join)
on c.field2 equals d.field2
// ^ here
into left_two
where a.field1 == theValueImSearchingFor
from c in left_one.DefaultIfEmpty()
from d in left_two.DefaultIfEmpty()
select new CombinedObject()
{
...
}
The reason I am using on c.field2 equals d.field2 in the third join statement is that my tables are structured like this:
tableA: field1
tableB: field1
tableC: field1 field2
tableD: field2
That is, the only way to relate tableD to the rest of the data is to use field2.
Can someone please correct my syntax? Or is there a certain way I have to do it given my setup of tables?
I use this type of syntax:
var results = (from a in db.tableA
from b in db.tableB.Where(s => s.field1 == a.field1)
from c in db.tableC.Where(s => s.field1 == a.field1).DefaultIfEmpty()
from d in db.tableD.Where(s => s.field2 == c.field2).DefaultIfEmpty()
select new CombinedObject() { });
It seems to work well on multiple tables. I think I got my field1s and field2s right to match your example :)
[Edit]
As per the comment, if you want to add in some additional filtering, you just add it in where appropriate into the Where(). Eg:
from c in db.tableC.Where(s => s.field1 == a.field1 && s.field3 == someVariable).DefaultIfEmpty()
Something like that :)
I am attempting to run the following LINQ query using Entity Framework 5:
int taskId = 2;
query = from a in Table_A
where a.StatusCode != "DONE"
&& a.Inbound
join b in Table_B
on a.Id equals b.Id_Table_A
join c in Table_C
on a.State equals (c.State ?? a.State)
where 2 == c.Id_Task
&& b.DataType == c.DataType
select a.Id;
The line that is causing me problems is:
on a.State equals (c.State ?? a.State)
The "State" field in Table_C is nullable... and when it is null, it is used to imply "all states". As such, when "c.State" is null I want the record to be matched. If I were to write this in SQL, I would use the following:
JOIN Table_C ON Table_A.State = ISNULL(Table_C.State, Table_A.State)
Unfortunately, I am being given the following error:
The name 'a' is not in scope on the right side of 'equals'. Consider swapping the expressions on either side of 'equals'.
I will be grateful to anybody who can let me in on the secret to getting this working.
Thanks.
You can modify your code like:
int taskId = 2;
query = from a in Table_A
where a.StatusCode != "DONE"
&& a.Inbound
join b in Table_B
on a.Id equals b.Id_Table_A
from c in Table_C
where 2 == c.Id_Task
&& b.DataType == c.DataType
&& (c.State == null || a.State.Equals(c.State))
select a.Id;
A join is essentially a where clause, so here we can use the where clause due to the restrictions with join.
I managed to get this to work by moving the "DataType" check from the WHERE to the JOIN, and moving the "State" check from the JOIN to the WHERE. The resulting code that worked as I expected is as follows:
query = from a in Table_A
where a.StatusCode != "DONE"
&& a.Inbound
join b in Table_B
on a.Id equals b.Id_Table_A
join c in Table_C
on b.DataType equals c.DataType
where 2 == c.Id_Task
&& (c.State ?? a.State) == a.State
select a.Id;
Many thanks to everybody who has taken a look at this for me. :)
You can use "from" syntax instead of "join"
from a in TableA
from b in TableB
.Where(x => (x.Buy ?? a.Buy) == a.Buy
&& (x.Parity ?? a.Parity) == a.Parity)
In SQL I'd say:
select a.*
from TableA a
left join TableB b on a.Type = b.Type and a.SomeDate < b.AnotherDate
where b.ID is null
This would select all records in TableA where no record exists in TableB of the same Type and later date.
In Linq, how do you do this?
from a in TableA
join b in TableB on a.Type equals b.Type into j // what about the comparator?
from x in j.DefaultIfEmpty()
where x == null
select a;
Thanks!
EDIT:
A few good answers have been proposed, all of which address the specific need expressed in this question, but they're all basically workarounds. They all translate to a nested "exists" queries in one way or another, whereas the SQL in the question is one neat query without any nesting. The case given here is just an example of a general principle; what I'd really like to see is a Linq expression that will translate to (roughly) the syntax of the above SQL query.
Something like this ought to help:
var results =
(from itemA in TableA
from itemB in TableB
where itemA.Type != itemB.Type && itemA.Date < itemB.Date
select itemA).Distinct();
from a in tableA
let rights =
from b in tableB
where a.Type == b.Type && a.Date < b.Date
select b
where !rights.Any()
select a;
It's translated into:
SELECT [t0].[Type] AS [Type], [t0].[SomeDate] AS [SomeDate]
FROM [TableA] AS [t0]
WHERE NOT (EXISTS(
SELECT NULL AS [EMPTY]
FROM [TableB] AS [t1]
WHERE ([t0].[Type] = [t1].[Type]) AND ([t0].[SomeDate] < [t1].[AnotherDate])))
var results = TableA.Where(a =>
!TableB.Any(b => a.Type == b.Type && a.Date < b.Date))
If you want the linq query to be exactly as your SQL you can write:
var result = from a in TableA
from b in TableB.Where(b => a.Type = b.Type && a.SomeDate < b.AnotherDate).DefaultIfEmpty()
where b == null
select a;
But I would say that the first solution is better as the where b == null would result in a filter operation in the queryplan.