How to rewrite sql query to linq - c#

I'm trying to rewrite sql query to linq but can't do it myself.
The most problem for me is to get I,II and III aggregated values.
Sql query:
select o.Name,t.TypeID, SUM(e.I),SUM(e.II),SUM(e.III) from Expenditure e
join Finance f on f.FinanceId = e.FinanceId
join FinanceYear fy on fy.FinanceYearId = f.FinanceYearId and fy.StatusId = 1
join Project p on p.ProjectId = fy.ProjectId
join Organization o on o.OrganizationId = p.OrganizationId
join Type t on t.TypeID = p.TypeID
where fy.Year = 2018
group by o.Name,s.TypeID
and what I have done so far is:
var x = (from e in _db.Expenditures
join f in _db.Finances on e.FinanceId equals f.FinanceId
join fy in _db.FinanceYears on f.FinanceYearId equals fy.FinanceYearId and fy.StatusId = 1 // this does not work, cant join on multiple conditions?
join p in _db.Projects on fy.ProjectId equals p.ProjectId
join o in _db.Organizations on p.OrganizationId equals o.OrganizationId
join s in _db.Types on p.TypeId equals s.TypeId
group new { o, s } by new { o.OrganizationId, s.TypeId }
into grp
select new AggModel
{
OrganizationId = grp.Key.OrganizationId,
TypeId = grp.Key.TypeId,
I = ?,
II = ?,
III = ?,
}
);

Try something like this:
group new { e, o, s } by new { o.OrganizationId, s.TypeId }
into grp
select new AggModel
{
OrganizationId = grp.Key.OrganizationId,
TypeId = grp.Key.TypeId,
I = grp.Sum(a => a.e.I),
II = grp.Sum(a => a.e.II),
III = grp.Sum(a => a.e.III),
}
You'll need to adjust the right side of the lambda to navigate to the correct property.

You Need to use the Group by for aggregation methods.
Check the below link for more Knowledge.
How to use aggregate functions in linq with joins?

Related

How to make left join and group by in linq?

I want to join 3 tables 2 of them inner join one of them left join after that i want to make group by. However, it gives an error. How can I handle that ?
this is code :
var people = from u in db.User.ToList()
join o in db.Offer.ToList() on u.UserId equals o.UserID where o.Statu == "Accepted"
join oz in db.log.ToList() on new { x1 = u.UserId.ToString(), x2 = o.CampaignId.ToString() } equals new { x1 = oz.ID, x2 = oz.CampaignID } into ps
from tbl in ps.DefaultIfEmpty()
group new { u, o, tbl } by new { u.UserId, o.CampaignId, o.Target, tbl.ID} into grp
select new { Username = grp.Key.UserId, CampaignID= grp.Key.CampaignId, Target = grp.Key.Target, id = grp.Key.ID};
Error occurs when i use tbl in group by. But i need to use it. I think some values comes null so it gives an error. How can i handle this ?

Translate nested select of oracle query to linq

I was given an oracle query and am trying to translate it to linq. I have been successful up to the point of the inner select.
select distinct pm.projNumber, nvl(s.submission_nbr, ppo.submission_nbr) submission_nbr, nvl(ot.objectname, pot.objectname) objectname , wa.assigned, f.lname, f.fname
from wfassignment wa
join CodeTab c on c.codeid = wa.appr_stat
join projobject po on po.objectid = wa.objectid
join projmain pm on pm.projid = po.projid
join hhistory s on s.Prop_no = pm.Prop_No and s.Inst_Code = pm.Inst_Code and pm.System = 'foo' and s.mark = po.mark
left join objecttypes ot on ot.objecttype = po.objecttype and ot.system = pm.system
left join(
select a.mark, a.objecttype, a.submitdate, c.submission_nbr
from projobject a
join b on b.projid = a.projid
join c on c.Prop_no = b.Prop_No and c.Inst_Code = b.Inst_Code and b.System = 'foo' and c.mark = a.mark ) ppo on ppo.mark = s.parentmark
left join objecttypes pot on pot.objecttype = ppo.objecttype and pot.system = pm.system
join faculty f on f.unique_id = wa.unique_id
where wa.completed is null and wa.unique_id in ('foo', 'bar', 'foo', 'bar')
below is my C# code up until "left join (select... )"
var pageObject = (
from wa in db.WFASSIGNMENTs
join c in db.CODETABs on wa.APPR_STAT equals c.CODEID
join po in db.PROJOBJECTs on wa.OBJECTID equals po.OBJECTID
join pm in db.PROJMAINs on po.PROJID equals pm.PROJID
join s in db.HHISTORies on new { pm.PROP_NO, pm.INST_CODE, po.MARK } equals new { s.PROP_NO, s.INST_CODE, s.MARK }
join ot in db.OBJECTTYPES on new { OBJECTTYPE = po.OBJECTTYPE, pm.SYSTEM } equals new { OBJECTTYPE = ot.OBJECTTYPE1, ot.SYSTEM }
How do I translate the inner select to linq?
I pulled out the inner select into another variable and just joined that variable. Did the trick.

Translate SQL statement with SUM() in Entity

I try to translate this SQL code :
SELECT w.Id, w.LastName, w.FirstName, SUM(d.Price*dt.Number) AS somme
FROM Waiter w
INNER JOIN Client c on w.Id = c.WaiterId
INNER JOIN DisheOnTable dt on c.Id = dt.ClientId
INNER JOIN Dishe d on dt.DisheId = d.Id
GROUP BY w.Id, w.LastName, w.FirstName
ORDER BY somme DESC;
in entity framework.
I tried something like this
var query2 = (from w in db.Waiter
join c in db.Client on w.Id equals c.WaiterId
join dt in db.DisheOnTable on c.Id equals dt.ClientId
join d in db.Dishe on dt.DisheId equals d.Id
group w by new { w.Id, w.LastName, w.FirstName } into g
//orderby g.Select() descending
select new
{
id = g.Key.Id,
lastname = g.Key.LastName,
firstname = g.Key.FirstName,
total = g.Sum(q => q.)
});
but my sum doesn't work (after multiple research and try) and i don't know how to multiply my variables.
PS : The SQL statement works well, i tried it.
Thank you for helping guys ! :)
You need to group on both dish and DishOnTable alias as Price is in Dish and Number is in DishOnTable:
group new{ d,dt} by new {w.Id, w.LastName, w.FirstName} into g
and now sum the columns which you want from it
select new {
id = g.Key.Id,
lastname = g.Key.LastName,
firstname = g.Key.FirstName,
total = g.Sum(q => q.d.Price * q.dt.Number)
}).OrderBy(x=>x.total)

linq to sql distinct values or group by

I have the folowing linq query.
How can I modify the query to return distinct values for CityFoo property only?
var query = from f in db.Foos
join b in db.Bars on f.IDFoo equals b.IDFoo
join fb in db.Fubars on b.IDBar equals fb.IDBar
select new MyViewModel {
IDFoo = f.IDFoo,
NameFoo = f.NameFoo,
CityFoo = f.CityFoo,
NameBar = b.NameBar,
NameFubar = fb.NameFubar };
I think you are missing information on your query.
If you want the first value to be used on the other properties, you need to tell that to Linq
So I am guessing that you actually want to group and then take the first.
Or...something like this:
var query = from f in db.Foos
join b in db.Bars on f.IDFoo equals b.IDFoo
join fb in db.Fubars on b.IDBar equals fb.IDBar
group new { f, b, fb } by f.CityFoo into grp
let first = grp.FirstOrDefault()
select new MyViewModel {
IDFoo = first.f.IDFoo,
NameFoo = first.f.NameFoo,
CityFoo = grp.Key,
NameBar = first.b.NameBar,
NameFubar = first.fb.NameFubar };

LINQ - multi join with Group by and get average

I'm trying to write this select in LINQ but Im not successful to fix it for long time. I also tried LINQ - join with Group By and get average but it doesn't work in my code. It is obviously that I'm wrong.
SQL:
SELECT name_type, AVG(t.price) as avgPrice FROM type tp
JOIN location l ON l.ID_type = tp.ID
JOIN event e ON e.ID_location = l.ID
JOIN ticket t ON t.ID_event = e.ID
GROUP BY tp.name_type
LINQ:
var q3 = from l in db.location
join tp in db.type on l.ID_type equals tp.ID
join e in db.event on l.ID equals u.ID_location
join t in db.ticket on e.ID equals t.ID_event
group tp by new {Type_name = tp.type_name} into grp
select new
{
Type_name = grp.Key.type_name,
avgPrice = grp.Average( x => x.ticket.price)
};
There are a few problems:
There is an error in the second join—I believe u.ID_location needs to be e.ID_location.
I think you are grouping on the wrong entity, try grouping by t instead of tp.
You don't need the anonymous type in the group by.
Try this:
var results =
from l in db.location
join tp in db.type on l.ID_type equals tp.ID
join e in db.event on l.ID equals e.ID_location
join t in db.ticket on e.ID equals t.ID_event
group t by new tp.type_name into grp
select new
{
Type_name = grp.Key,
avgPrice = grp.Average(x => x.price)
};
If you happen to have navigation properties set up between your entities, this would be a lot easier. It's pretty hard to tell how the entities are supposed to be related, but I'm thinking something like this would work:
// average ticket price per location type
var results =
from t in db.ticket
group t by t.event.location.type.type_name into g
select new
{
Type_name = g.Key,
avgPrice = g.Average(x => x.price)
};
Or in fluent syntax:
var results = db.ticket.GroupBy(t => t.event.location.type.type_name)
.Select(g => new
{
Type_name = g.Key,
avgPrice = g.Average(x => x.price)
});

Categories