Consider these 2 classes.
class OrderDetail {int Specifier;}
class Order
{
OrderDetail[] Details;
}
Now I have a List I want to enumerate over, selecting only the objects with a Specifier of 1. As this is easy in SQL I thought LINQ with a join would be good for this but I dont know how to build the query.
from o in orders join o in o.Details on o.Id equals od.Id where od.Specifier = 1 select od
This gives an error that 'o' does not exist in the current context after join.
What am I doing wrong here?
orders.SelectMany(o => o.Details.Where(od => od.Specifier == 1))
In your query you are using same sequence variable name o for details, you should use join od in o.Details. But join is not needed here, because order already contains details:
from o in orderes
from od in o.Details
where od.Specifier == 1
select od
Related
Thanks in advance for any help.
Not an expert in Linq to Sql by any means.
I have 4 tables.
The main lb_item table which defines, unsurprisingly, an item.
Many fields but holds 3 ID fields.
itemID (key)
categoryID (not null)
patternID (can be null)
lb_pattern table which is keyed off the lb_item patternID.
lb_category table which is keyed off the lb_item categoryID.
lb_animal table which is keyed off the lb_item item ID.
So I need a select from the lb_item table joining to these other 3 tables to bring back varchar fields as I'm building a DTO.
A single left outer join works fine thus:
from lbi in lbContext.lb_item
join lbp in lbContext.lb_pattern on lbi.patternID equals lbp.patternID into g1
from j1 in g1.DefaultIfEmpty()
join lbc in lbContext.lb_category on lbi.categoryID equals lbc.categoryID
where lbi.itemID == id
select new lb_itemDTO..........
I now need to add a 2nd left outer join for the lb_animal table.
So I started to do this:
from lbi in lbContext.lb_item
join lbp in lbContext.lb_pattern on lbi.patternID equals lbp.patternID into g1
from j1 in g1.DefaultIfEmpty()
join lba in lbContext.lb_animal on j1.
But the options in VS for j1 give me only the fields within the lb_pattern table.
I need the join to read:
join lba in lbContext.lb_animal on j1.itemID equals lba.itemID
or
join lba in lbContext.lb_animal on lbi.itemID equals lba.itemID
Neither works and gives me an exception along the lines of "'NavigationExpandingExpressionVisitor' failed. This may indicate either a bug or a limitation in EF Core".
So how can I add a left outer join to the lb_animal table?
I've spent the last hour looking at various SO posts to suss it out but I just cannot seem to get my head around the solution for some reason. Feel like a newbie. And I'm sure the solution is going to be obvious!
Any help or pointers to a solution would be much appreciated.
This should work:
var ans = from lbi in lbContext.lb_item
where lbi.itemID == id
join lbp in lbContext.lb_pattern on lbi.patternID equals lbp.patternID into lbpj
from lbp in lbpj.DefaultIfEmpty()
join lba in lbContext.lb_animal on lbi.itemID equals lba.itemID into lbaj
from lba in lbaj.DefaultIfEmpty()
join lbc in lbContext.lb_category on lbi.categoryID equals lbc.categoryID
select new {
};
Persvered and finally came across a SO post which approached it in a different way and it worked.
Original SO is here:
My working code is now thus:
from lbi in lbContext.lb_item
from lbc in lbContext.lb_category
.Where(c => c.categoryID == lbi.categoryID)
from lbp in lbContext.lb_pattern
.Where(p => p.patternID == lbi.patternID)
.DefaultIfEmpty()
from lba in lbContext.lb_animal
.Where(a => a.itemID == lbi.itemID)
.DefaultIfEmpty()
where lbi.itemID == id
select new lb_itemDTO
Would still be interested in comments on this solution as it's not breaking the outer joins into grouped segments. So is this solution I found any less efficient in terms of the SQL it generates compared to how I was originally proposing to do it?
Please note below is entirely made up for example sake. I have a similar query based on an sql code but couldn't translate it to LINQ to get correct value.
The sql basically looks like this:
select * from customers c
join proucts p on c.id = p.customerid
join credit r on r.customerid=c.id and ISNULL(r.trandate, c.registeredDate) >= c.registeredDate
I also tried to tweak the above sql and put the condition inside where and it also returns the same value I am getting in my #2 LINQ below(which is incorrect).
How can I use c (customer) inside .Where of credit? see code
1.
from c in customers
join p in products on c.id = p.customerid
join cr in credit.Where(r=> r.tranDate => c.registeredDate!=null?c.registeredDate : r.purchaseDate) on c.id=cr.customerid
...
2.
I know you would suggest why not just put it in a where below like below but I am getting incorrect value.
from c in customers
join p in products on c.id = p.customerid
join cr in credit on c.id=cr.customerid
where r.tranDate => c.registeredDate!=null?c.registeredDate : r.purchaseDate
Is there a workaround? I have tried tons of others but won't get me the correct one.
LINQ supports only equijoins. Any additional criteria should go to where clause. And yes, the other range variables are inaccessible from the join inner sequence, so the filtering should happen before or after the join.
So this SQL query:
select * from customers c
join products p on c.id = p.customerid
join credit r on r.customerid = c.id
and ISNULL(r.trandate, c.registeredDate) >= c.registeredDate
directly translates to this LINQ query:
from c in customers
join p in products on c.id equals p.customerid
join cr in credit on c.id equals cr.customerid
where (cr.tranDate ?? c.registeredDate) >= c.registeredDate
select new { c, p, cr };
Optionally, the condition
(cr.tranDate ?? c.registeredDate) >= c.registeredDate
can be replaced with
(cr.tranDate == null || cr.tranDate >= c.registeredDate)
I want to have join query from a table with a dictionary based on a common field, my query is:
var query = from c in db.Exp
join d in lstUniprotDic on c.UniID equals d.Key
select new
{
c.UniID,
IdentityPercent=d.Value.ToString(),
c.PrId,
c.SpotNo
}
but i got the following error
Local sequence cannot be used in LINQ to SQL implementation of query operators except the Contains() operator.
That pretty much says it all. You can't use the dictionary in your LINQ to SQL query except when using Contains.
Solution:
(from c in db.Exp where lstUniprotDic.Keys.Contains(c.UniID) select c).AsEnumerable()
join d in lstUniprotDic on c.UniID equals d.Key
select new
{
c.UniID,
IdentityPercent=d.Value.ToString(),
c.PrId,
c.SpotNo
}
I am not sure if the usage of lstUniprotDic.Keys in the LINQ to SQL query is actually working.
If not, try using this code instead:
var ids = lstUniprotDic.Keys.ToArray();
(from c in db.Exp where ids.Contains(c.UniID) select c).AsEnumerable()
join d in lstUniprotDic on c.UniID equals d.Key
select new
{
c.UniID,
IdentityPercent=d.Value.ToString(),
c.PrId,
c.SpotNo
}
I have 3 data tables: a; b; and c. In this I need to write Join Query Dynamically using LINQ.
The Selecting columns given by customer and Condition columns also given customer at run time.
So I need to create queries dynamically. Please check below example. Because I don't know which table they want and which column also
For example
Select a.c1,a.c2,b.c1,b.c2 From a Left Join b on a.c1=b.c1
Select c.c1,c.c2,a.c1,a.c2 From c Left Join a on c.c3=a.c1
Select a.c1,a.c2,b.c1,b.c2,c.c1,c.c2 From a Left Join b on a.c2=b.c2 Left join c on c.c1=a.c1
Like I need create different set of queries. Please help me on this.
You could use either System.Linq.Dynamic(ScottGu's blog article and nuget) in case of dynamic where clause:
var results = (from fruit in fruits
join car in cars on fruit.Id equals car.Id
select new { fruit, car })
.AsQueryable()
.Where("fruit.ColA != car.ColA")
.Where("fruit.ColB == car.ColB");
Or dynamicaly build expressions this using extensions from PredicateBuilder writen by #joe-albahari. For example:
var predicate =
PredicateBuilder
.True<Tuple<Product, Product>>()
.And(t => t.Item1.ColA != t.Item2.ColA)
.And(t => t.Item1.ColB == t.Item2.ColB)
.Compile();
(from fruit in fruits
join car in cars on fruit.Id equals car.Id
select Tuple.Create(fruit, car))
.Where(predicate)
.Dump();
ps: full code available at gisthub
I had tried to join two table conditionally but it is giving me syntax error. I tried to find solution in the net but i cannot find how to do conditional join with condition. The only other alternative is to get the value first from one table and make a query again.
I just want to confirm if there is any other way to do conditional join with linq.
Here is my code, I am trying to find all position that is equal or lower than me. Basically I want to get my peers and subordinates.
from e in entity.M_Employee
join p in entity.M_Position on e.PostionId >= p.PositionId
select p;
You can't do that with a LINQ joins - LINQ only supports equijoins. However, you can do this:
var query = from e in entity.M_Employee
from p in entity.M_Position
where e.PostionId >= p.PositionId
select p;
Or a slightly alternative but equivalent approach:
var query = entity.M_Employee
.SelectMany(e => entity.M_Position
.Where(p => e.PostionId >= p.PositionId));
Following:
from e in entity.M_Employee
from p in entity.M_Position.Where(p => e.PostionId >= p.PositionId)
select p;
will produce exactly the same SQL you are after (INNER JOIN Position P ON E..PostionId >= P.PositionId).
var currentDetails = from c in customers
group c by new { c.Name, c.Authed } into g
where g.Key.Authed == "True"
select g.OrderByDescending(t => t.EffectiveDate).First();
var currentAndUnauthorised = (from c in customers
join cd in currentDetails
on c.Name equals cd.Name
where c.EffectiveDate >= cd.EffectiveDate
select c).OrderBy(o => o.CoverId).ThenBy(o => o.EffectiveDate);
If you have a table of historic detail changes including authorisation status and effective date. The first query finds each customers current details and the second query adds all subsequent unauthorised detail changes in the table.
Hope this is helpful as it took me some time and help to get too.