Having trouble with Group by and Join EF c# - c#

I am having trouble converting this T-SQL code into EF C#
select
se.pcname, count(u.usrid) as total
from
tbusers as u
inner join
tbhcontainer as hc on u.hcid = hc.hcid
inner join
tbusersettings as se on hc.sid = se.sid
where
day(u.created) = 18
group by
se.pcname
order by
total desc
tbusers:
Username, PCName, Usrid, Created, HCID
tbhcontainer:
hcid, sid
tbusersettings:
sid, pcname
EDIT 1:
DateTime yesterday = DateTime.UtcNow.Date.AddDays(-1).AddHours(-3);
DB_121002_psmainEntities ctx = new DB_121002_psmainEntities();
var res = from r in ctx.tbusers
join hc in ctx.tbhcontainers on r.hcid equals hc.hcid
join s in ctx.tbUserSettings on hc.sid equals s.sid
group s by s.pcname
where r.created >= yesterday || r.created <= DateTime.Today
select r;
return res.Count();
It fails on all levels, just don't know how to use group by with joined tables

A direct translation would look more like this:
from u in ctx.Users
join hc in ctx.HContainers on u.Hcid equals hc.Hcid
join us in ctx.UserSettings on hc.Sid equals us.Sid
where u.Created.Day == 18
group u.Userid by us.Pcname into g
let total = g.Count()
orderby total descending
select new
{
pcname = g.Key,
total,
}
If you have additional clauses after the grouping, you need to place the results into another variable (g). Then you can access the group key and perform any aggregating function on that group.

Related

LINQ Trouble with nested subquery in select statement

I have the following query I want to replicate in LINQ:
SELECT A.id,C.quotas, C.fundingid, C.date
,(SELECT value FROM public.fundingsharevalue WHERE fundingid = C.fundingid AND date = C.date) as sharevalue
FROM public.goal A
INNER JOIN public.goaltransactionfunding C ON A.id = C.goalid
where A.userid = 25
Code in LINQ:
var balance = from goal in _context.Goals
join goaltransactionfunding in _context.Goaltransactionfundings on goal.Id equals goaltransactionfunding.Goalid
join user in _context.Users on goal.Userid equals user.Id
where goal.Userid == userid
select new BalanceViewModel
{
FundingId = goaltransactionfunding.Fundingid,
ShareValue = (from fundingsharevalue in _context.Fundingsharevalues
where fundingsharevalue.Id == goaltransactionfunding.Fundingid && fundingsharevalue.Date.Equals(goaltransactionfunding.Date)
select fundingsharevalue.Value).FirstOrDefault(),
Quotas = (double)goaltransactionfunding.Quotas,
Fecha = goaltransactionfunding.Date,
GoalId = goal.Id
};
The problem is with Sharevalue subquery, it doesn't show values when actually it has.
It seems that the query does not fetch anything when it should fetch as it does in SQL.
I'm attaching images for both outputs.
QueryShareValues Image
LINQ sharevalues Image

translate postgres sql to linq. Is it possible?

I need translate next sql to linq is it possible? That will have approximately the same speed
SELECT Count(tblcollectionimage.lngimageid),
tblcollectiontree.lngcollectionid,
tblcollection.txtname
FROM (tblcollectiontree
LEFT JOIN tblcollectionimage
ON blcollectiontree.lngcollectionid =
tblcollectionimage.lngcollectionid)
JOIN tblcollection
ON tblcollectiontree.lngcollectionid = tblcollection.lngcollectionid
WHERE lngcollectionparentid = 0
GROUP BY tblcollectiontree.lngcollectionid,
tblcollection.txtname
I have currently such linq but it doesn't work.
var results =(from collection in dataBase.tblcollections
join collectionTree in dataBase.tblcollectiontrees on
collection.lngcollectionid equals collectionTree.lngcollectionid
into generalCollections
from generalCollection in generalCollections
join images in dataBase.tblcollectionimages on
collection.lngcollectionid equals images.lngcollectionid
into generalCollectionImages
from generalCollectionImage in
generalCollectionImages.DefaultIfEmpty()
group generalCollectionImage by
generalCollectionImage.lngcollectionid into hello
from hellos in hello.DefaultIfEmpty()
join collection in dataBase.tblcollections on
hello.Key equals collection.lngcollectionid
select new
{
id = hello.Key,
name = hello.Count()
}).ToList();

Left outer join and multiple counts SQL to LINQ

How would this query using an inner join, left outer join, group by and two counts be converted to linq?
SELECT
c.EndowmentID,
COUNT(DISTINCT f.CriterionID) AS RequiredCriteria,
COUNT(r.ChoiceID) AS Response
FROM
Criteria c
INNER JOIN
Filters f
ON
c.ID = f.CriterionID
LEFT OUTER JOIN
Responses r
ON
f.ChoiceID = r.ChoiceID
WHERE
f.IsRequirement = 1
GROUP BY
c.EndowmentID;
This is what I have done so far:
var result =
from c in context.Criteria
join f in context.Filters on c.ID equals f.CriterionID
join r in context.Responses on f.ChoiceID equals r.ChoiceID into resfil
from rf in resfil.DefaultIfEmpty()
group rf by c.EndowmentID into grouped
select new
{
EndowmentID = grouped.Key,
Requirements = grouped.Count(t=>t.CriterionID),
Response = grouped.Count(t=>t.ChoiceID)
};
You need to group using an anonymous class. This will allow you to access all your tables in your select statement
group new { c, f, rf } by c.EndowmentID into grouped
SQL: COUNT(DISTINCT f.CriterionID) AS RequiredCriteria,
This can be written by first selecting the f.CriterionID column, Distinct(), Count()
RequiredCriteria = grouped.Select(x => x.f.CriterionID).Distinct().Count()
SQL: COUNT(r.ChoiceID)
Response = grouped.Select(x => x.rf.ChoiceID).Count()

Linq to SQL - Group By and Count

I'm trying to convert this query (already working)
SELECT Building.NAME, COUNT([User].ID)
FROM BuildingUser
INNER JOIN Building ON Building.ID = BuildingUser.ID_BUILDING
INNER JOIN [User] ON [User].ID = BuildingUser.ID_USER
GROUP BY Building.NAME
To Linq to SQL, but I don't know what I'm doing wrong. Look at my trying
from buildinguser in db.GetTable<BuildingUser>()
join building in db.GetTable<Building>()
on buildinguser.ID_BUILDING equals building.ID
join user in db.GetTable<User>()
on buildinguser.ID_USER equals user.ID
group building by building.NAME into grpBuilding
select new
{
building = grpBuilding.Key,
users =
};
I just need to group my Buildings and count how many users each one has.
Simply use the the Count method:
from buildinguser in db.GetTable<BuildingUser>()
join building in db.GetTable<Building>()
on buildinguser.ID_BUILDING equals building.ID
join user in db.GetTable<User>()
on buildinguser.ID_USER equals user.ID
group building by building.NAME into grpBuilding
select new
{
building = grpBuilding.Key,
users = grpBuilding.Count()
};

LINQ to EF, Left Join and group by clause

I have this SQL:
select o.prod_id, SUM(o.[count]) as [count]
into #otgr
from otgr o
where o.[date]<= #date
group by o.prod_id
select f.prod_id, SUM(f.[count]) as [count]
into #factory
from factory f
where f.[date]<= #date
group by f.prod_id
select p.name, p.id, f.[count] - ISNULL(o.[count],0) as av_count
from products p
join #factory f on f.prod_id = p.id
left join #otgr o on o.prod_id = p.id
where f.[count] - ISNULL(o.[count],0) > 0
How can I translate this into Linq? I'm stuck with this code:
from otgrr in db.otgr
where otgrr.date <= date
group otgrr by otgrr.prod_id into otgrs
from fac in db.factory
where fac.date <= date
group fac by fac.prod_id into facs
from prod in db.products
join fac2 in facs on prod.id equals fac2.Key
join otg2 in otgrs.DefaultIfEmpty(new {id = 0, av_count = 0 }) on prod.id equals otg2.Key
where (fac2.SUM(a=>a.av_count) - otg2.SUM(a=>a.av_count)) > 0
select new products { id = prod.id, name = prod.name, av_count = (fac2.SUM(a=>a.av_count) - otg2.SUM(a=>a.av_count))
Thank to everyone, and sorry for my bad english
You can also check LINQPad.
Of course, you can split this into multiple LINQ queries (after all, the execution is deferred, so it will be executed all as one single query, without using temporary tables. It should be faster in 99% of the cases).
But in your case it can be written more simply, by using navigation properties you probably have already set up:
var result= from p in products
select new {Name=p.Name,
Id = p.Id,
Count = p.Factories.Where(f=> f.date <= date).Sum(f=>f.Count)
- p.otgrs.Where(o=> o.date <= date).Sum(o=>o.Count)
};

Categories

Resources