Filter entities with a field from another entity in linq query c# - entity-framework

I wanna join some tables in linq query. The problem is that I can not filter one of entities with field of another entity. In the below code b.createDate is not defiend, how can I do this query in linq?
From a in context.A
Join b in context.B
On a.Id equals b.AId
Join c in context.C.where(x =>
x.createDate >= b.createDate)
On b.Id equals c.BId into g
From result in
g.DefaultIfEmpty()
Select result

You have to use from instead of join in this case. As documented: Collection selector references outer in a non-where case
var query =
from a in context.A
join b in context.B on a.Id equals b.AId
from c in context.C
.Where(x => x.BId == b.Id && x.createDate >= b.createDate)
.DefaultIfEmpty()
select c;

Related

Linq : Select Different Object Left Join

I've tow contracts and one query I want to select one of them based on join result , without using where clause,
from a in pContext
join c in vContext
on a.id equals c.id into av
from lav in av.DefaultIfEmpty()
if(lav != null )
{
select new DTO1()
{
a.id,
a.name,
lav.description
}
}
else
{
select new DTO2()
{
a.id,
a.name
}
}
EF Core translates LINQ "left join" to SQL left join and you do not need to handle nulls in this case, because it expects values from DbDataReader. Simple projection should work:
var query =
from a in pContext
join c in vContext on a.id equals c.id into av
from lav in av.DefaultIfEmpty()
select new DTO1
{
a.id,
a.name,
lav.description
};
from a in pContext
join c in vContext
on a.id equals c.id into av
from lav in av.DefaultIfEmpty()
select new DTO()
{
id = a.id,
name = a.name,
description = lav != null ? lav.description : "No Specified"
}
The solution is based on Svyatoslav Danyliv comment using ternary operator but with different condition to avoid the NullReferenceException.

How do you use group by and having clause in EF with parent/child relationship?

How can I write a linq to entities query that includes a group by and a having clause?
For example in SQL:
SELECT * FROM dbo.tblParent p
INNER JOIN
(
SELECT a.ID
FROM dbo.tblParent a
join dbo.tblChild c ON a.ID = c.FkParentID
WHERE a.ColValue = 167
GROUP BY A.ID
HAVING COUNT(c.ID) = 1
) t ON p.ID = t.ID
I found my own answer.
// this is far from pretty but it works as far as I can tell
Apps = (from x in context.tblParents
join t in (
from p in context.tblParents
join c in context.tblChilds
on p.ID equals c.FkParentID
where p.ColValue == 167
group c.ID by p.ID into grouped
where grouped.Count() == 1
select new { grouped.Key }) on x.ID equals t.Key
select x);

GROUP and SUM in Entity Framework

I want to select sum of all (paid) prices of an order item for each customer.
Here is SQL command:
SELECT c.name,SUM(oi.price * oi.count) from customer c
JOIN order o ON c.id=o.customer_id
JOIN order_item oi ON o.id=oi.order_id
JOIN bill b ON b.id=oi.bill_id
WHERE b.payment_id is NOT null
GROUP by c.name;
I don't know how to do this in EF.
Example result:
John Smith 1500,2
Allan Babel 202,0
Tina Crown 3500,78
(comma is used as decimal point..because price is decimal value)
Your example result doesn't seem to match your SQL command, but i think you are looking for something like this:
var query = from c in context.Customers
join o in context.Orders on c.id equals o.customer_id
join oi in context.OrderItems on o.id equals oi.order_id
join b in context.bill on oi.bill_id equals b.id
where b.payment_id != null
group oi by c.name into g
select new
{
Name = g.Key,
Sum = g.Sum(oi => oi.price * oi.count),
}

Entity SQL selecting from more then 3 tables

I am new to Entity framwork and currently trying hard to get used this programming paradigm. I have this query which i want to write in Entity SQL.
SELECT f.id, f.personName, c.Category, j.busCode, s.description, f.StartDate, (SELECT COUNT(*) FROM Analysis WHERE id = f.id) As numOfAnalysis
FROM forms f
INNER JOIN Jobs j ON f.id = j.id
INNER JOIN category c ON j.categoryid = c.categoryid
INNER JOIN stage s ON f.stageid = s.stageid
WHERE j.busCode NOT IN ('xyz', 'YYY')
ORDER BY startDate
I can get records from two tables but as soon as i add third table using the navigation property, i get error table category is not loaded in the current context. I am using .net 3.5. Keep in mind that EDM V2 doest not have foreign keys and i think the only way to traverse through the table relationship is navigation property.
Any help will be deeply appreciated.
Thanks
Coder74
If you use should be able to mount this Linq query.
I tried to put together, but in the rush and no such test is complicated.
You can use this reference as support: http://code.msdn.microsoft.com/101-LINQ-Samples-3fb9811b
var result = (from f in forms
join j in Jobs on f.id equals j.id
join c in Category on j.categoryid equals c.categoryid
join s in stage on f.stageid equals s.stageid
join a in Analysis on a.id equals f.id
where !(new int[] { 'xyz', 'YYY' }).Contains(j.busCode)
orderby f.StartDate
select {
id =f.id,
personName = f.personName,
Category = c.Category,
busCode = j.busCode,
description = s.description,
StartDate = f.StartDate,
numOfAnalysis = a.Count()
}).ToList()
Julio Spader
W&S Soluções de Internet

Using multiple resultsets combined with joins in T-SQL

I'm currently using joins inside my stored procedures for outputting elements from different tables. An aggressive example
select a.*, b.*, c.*, d.*, e.*, f.* from tableA a
join tableB b on a.id = b.foreignid
join tableC c on b.id = c.foreignid
join tableD d on c.id = d.foreignid
join tableE e on d.id = e.foreignid
join tableF f on e.id = f.foreignid
where a.id = 1
It's getting pretty unhandy to work with when mapping the output to entities in my C# code, since I have to maintain a lot of boilerplate code.
Instead I would look into using multiple resultsets, so that I could map each resultset into an object type in code.
But how would I go around achieving this when I my case the different results would all relate to each other? The examples I've been able to find all revolved around selecting from different tables where the data were not related by foreign keys like mine. If I were to ouput my result in multiple resultsets the only thing I can come up with is something like this
select a.* from tableA
where a.id = 1
select b.* from tableB
join tableA a on a.id = b.foreignid
where a.id = 1
select c.* from tableC
join tableB b on b.id = c.foreignid
join tableA on a.id = b.foreginid
where a.id = 1
select d.* from tableD
join tableC c on c.id = d.foreignid
join tableB b on b.id = c.foreignid
join tableA a on a.id = b.foreignid
where a.id = 1
select e.* from tableE
join tableD d on d.id = e.foreignid
join tableC c on c.id = d.foreignid
join tableB b on b.id = c.foreignid
join tableA a on a.id = b.foreignid
where a.id = 1
select f.* from tableF
join tableE e on e.id = f.foreignid
join tableD d on d.id = e.foreignid
join tableC c on c.id = d.foreignid
join tableB b on b.id = c.foreignid
join tableA a on a.id = b.foreignid
where a.id = 1
But this is not cleaner, a lot more ineffecient (I would suppose, since there's alot more join statements)
Is it possible to use multiple resultset in this way I'm trying to? I just don't know how I would write the sql statements in the stored proc without having to do massive joins per resultset as in the example. And with the current solution I get an explosion of columns since I join them all together
You can actually return multiplte resultsets from a single SP and consume them in c#, check this post for instance : http://blogs.msdn.com/b/dditweb/archive/2008/05/06/linq-to-sql-and-multiple-result-sets-in-stored-procedures.aspx
It's a lesser known feature but sounds like what you're asking for. You don't have to join them and return them as a flattend rowset, just get the seperate rowsets and piece them together in memory.
Also you may want to read up on ORM frameworks, that could save you a lot of typing that you coud spend on features if it fits your needs.
https://stackoverflow.com/questions/249550/what-orm-frameworks-for-net-do-you-like-best
Regards GJ