How to convert SQL query to LINQ with Orderby, Groupby - c#

I am writing to write this SQL query in linq, but didnt work..
select [ProcessTime], Count([ID]) as 'amount of processes'
from [DB].[dbo].[TableX]
where [ID] in ('ServerX', 'ServerY') and [Type] ='Complete'
group by [ProcessTime]
order by [ProcessTime]
I would like to achieve this linq & what I have tried , I split the query into two, one for process time group by clause and another to count the ID's
var query1 = (from a in this.db.Processes
where (a.ID =='ServerX' || a.ID =='ServerY') && a.Type =='Complete'
group a by a.ProcessTime into b
//here I dont know where to place orderby
select b);
var query2 = (from a in this.db.Processes
where (a.ID =='ServerX' || a.ID =='ServerY') && a.Type =='Complete'
orderby a.ProcessTime
select a).Count();
is this the right way to split the query into two and then later combine them ?

Try this:
var serverNames = new string[]{"ServerX", "ServerY"};
var result = db.Processes
.Where(p => serverNames.Contains(p.ID) && p.Type == "Complete")
.GroupBy(p => p.ProcessTime)
.Select(g => new
{
ProcessTime = g.Key,
AmountOfProcesses = g.Count()
})
.OrderBy(x => x.ProcessTime);

You can do all this in one query:
var query1 = (from a in this.db.Processes
where (a.ID == "ServerX" || a.ID == "ServerY") && a.Type == "Complete"
group a by a.ProcessTime into b
orderby b.Key
select new {ProcessTime = b.Key, Count = b.Count()});

Related

Linq SQL with Select MAX Sub Query

I have the following SQL query which has a sub query so that only the max value is in the result set:
Select
t.ID,
r.ResultIdentifier,
p.ProductID,
r.Status,
r.Start
from Result r , Transact t, Product p
WHERE r.ResultIdentifier = (Select MAX(r2.ResultIdentifier) from Result r2
where r2.Status = 'Fail'
and r2.ID = r.ID
and r2.Start >= getdate() - 30)
and r.ID = t.ID
and p.productID = 9
and t.productID = p.productID
I'm trying to convert this to a LINQ query
var failures = from result in db.Results
join transact in db.Transacts on result.ID equals transact.ID
join product in db.Products on transact.ProductID equals product.ProductID
where result.ResultIdentifier == ??
.....
select new{ ID = transact.ID,
...etc
I'm really struggling with the max ResultIdentifier in the LINQ - tried multiple variations with .MAX() but cant seem to get it right.Any suggestions welcome.
You can use the max keyword, Sorry for using method syntax as I can see you are using query :(
Should look something like the following
where result.ResultIdentifier == (Results.Max().Where(x => x.Status.equals("Fail") && x.id == result.id && x.start => Datetime.Now().Add(-30)).Select(x => x.ResultIdentifier))
Try the following query:
var results = db.Results;
var failedResults = results
.Where(r => r.Status == "Fail" && r.Start >= DataTime.Date.AddDays(-30));
var failures =
from result in results
join transact in db.Transacts on result.ID equals transact.ID
join product in db.Products on transact.ProductID equals product.ProductID
from failed in failedResults
.Where(failed => failed.ID == result.ID)
.OrderByDescending(failed => failed.ResultIdentifier)
.Take(1)
where result.ResultIdentifier == failed.ResultIdentifier
.....
select new{ ID = transact.ID,
...etc

Problems recreating LINQ query from SQL script

I'm struggling in 'translating' a SQL query to a LINQ query. My SQL query looks like this:
SELECT S.SummonerName, LE.LeaguePoints, LS.DateTime, SUM(LE.LeaguePoints)
FROM LadderEntries LE
JOIN Sumonners S on LE.SummonerId = S.Id
JOIN LadderSnapshots LS on LE.LadderSnapshotId = LS.Id
WHERE LS.Region = 'euw1'
AND DateTime = '2019-06-14 00:00:00'
OR DateTime = '2019-06-13 00:00:00'
and LS.Region = 'euw1'
GROUP BY S.SummonerName
This query gives me the desired result. However, so far I got the following LINQ query:
from LE in _database.LadderEntries
join S in _database.Sumonners on LE.SummonerId equals S.Id
join LS in _database.LadderSnapshots on LE.LadderSnapshot.Id equals LS.Id
where LS.Region == param.Region && (LS.DateTime == param.Date || LS.DateTime == param.Date.AddDays(-1))
group new {LE, S, LS} by S.SummonerName
into C
select new GetLadderEntryDifferencesEntry
{
LpDifference = C.Select(a => a.LE.LeaguePoints).Sum(),
SummonerName = C.Select(a => a.S.SummonerName).FirstOrDefault()
};
But this gives me the error InvalidOperationException: Error generated for warning 'Microsoft.EntityFrameworkCore.Query.QueryClientEvaluationWarning: The LINQ expression 'GroupBy([S].SummonerName, new <>f__AnonymousType5'3(LE = [LE], S = [S], LS = [LS]))' could not be translated and will be evaluated locally.'. on execution.
I'm wondering what I'm doing wrong.
Note: I'm using sqllite and ef core if that makes a difference.
I believe the issue will be with:
&& (LS.DateTime == param.Date || LS.DateTime == param.Date.AddDays(-1))
try this:
var firstDate = param.Date;
var secondDate = param.Date.AddDays(-1);
then
&& (LS.DateTime == firstDate || LS.DateTime == secondDate)
possibly it may be taking exception to:
SummonerName = C.Select(a => a.S.SummonerName).FirstOrDefault()
or how the grouping is arranged.
Are these entities set up with references and can the expression be simplified?
var ladderEntryDifferences = _database.LadderSnapshots
.Where(x =>x.Region = param.Region
&& (x => x.DateTime == firstDate || x.DateTime == secondDate)
.GroupBy(x => x.LadderEntry.Summoner.SummonerName)
.Select( g => new GetLadderEntryDifferencesEntry
{
LpDifference = g.Sum(x => x.LeagueEntry.LeaguePoints),
SummonerName = g.Key // This will be the SummonerName
}).ToList();
The above is a guess about the structure, and pulling the group by from memory, but it might give you some ideas to try. If your context does not expose LadderSnapshots at a top level, you should be able to compose it from the LadderEntry level as well...
Ok here is what i got, first
LS.Region = 'euw1'
AND DateTime = '2019-06-14 00:00:00'
OR DateTime = '2019-06-13 00:00:00'
and LS.Region = 'euw1'
is not the same as the below linq, where the parameters is missing in the sql.
&& (LS.DateTime == param.Date || LS.DateTime == param.Date.AddDays(-1))
Now about the group by you could try to do it like this instead
from LE in _database.LadderEntries
join S in _database.Sumonners on LE.SummonerId equals S.Id
join LS in _database.LadderSnapshots on LE.LadderSnapshot.Id equals LS.Id
where LS.Region == param.Region && (LS.DateTime == param.Date || LS.DateTime == param.Date.AddDays(-1))
group LE by new {LE.SummonerName, S.SummonerName, LS.SummonerName}
into C
select new GetLadderEntryDifferencesEntry
{
LpDifference = C.Select(a => a.LE.LeaguePoints).Sum(),
SummonerName = C.Select(a => a.S.SummonerName).FirstOrDefault()
};

Yet another “A query body must end with a select clause or a group clause”

This query does work, but I am trying to combine the two steps into one query.
var query1 = from b in db.GetTable<Boats>()
from o in db.GetTable<Offices>()
from u in db.GetTable<Users>()
.Where
(u =>
u.UserId == b.Handling_broker &&
o.Office == b.Handling_office &&
b.Status == 2 &&
officesToInclude.Contains(b.Handling_office)
)
select new
{
hOffice = o.Name,
bName = u.Name
};
var query2 = query1.GroupBy(t => new { office = t.hOffice, name = t.bName })
.Select(g => new { Office = g.Key.office, Name = g.Key.name, Count = g.Count() });
If I try to combine the two queries using the following query it gives me the “A query body must end with a select clause or a group clause” error.
var query1 = from b in db.GetTable<Boats>()
from o in db.GetTable<Offices>()
from u in db.GetTable<Users>()
.Where
(u =>
u.UserId == b.Handling_broker &&
o.Office == b.Handling_office &&
b.Status == 2 &&
officesToInclude.Contains(b.Handling_office)
)
.GroupBy(t => new { office = t.Office, name = t.Name })
.Select(g => new { Office = g.Key.office, Name = g.Key.name, Count = g.Count() });
I think I have to add a select something, but I can't figure out what.
Can anyone please help?
Your query must contain a select clause. The .Where(...).GroupBy(...).Select(...) are only on the db.GetTable<Users>(). Something like:
var query1 = from b in db.GetTable<Boats>()
from o in db.GetTable<Offices>()
from u in db.GetTable<Users>().Where(u => u.UserId == b.Handling_broker &&
o.Office == b.Handling_office &&
b.Status == 2 &&
officesToInclude.Contains(b.Handling_office))
.GroupBy(t => new { office = t.Office, name = t.Name })
.Select(g => new { Office = g.Key.office, Name = g.Key.name, Count = g.Count() })
select new { /* Desired properties */};
But I think you are looking for something like:
var result = from b in db.GetTable<Boats>()
from o in db.GetTable<Offices>()
from u in db.GetTable<Users>()
where u.UserId == b.Handling_broker &&
o.Office == b.Handling_office &&
b.Status == 2 &&
officesToInclude.Contains(b.Handling_office))
group 1 by new { t.Office, t.Name } into g
select new { Office = g.Key.Office, Name = g.Key.Name, Count = g.Count() };

joining two from with an expression<func<>>

Is it possible to join two from based on a local expression variable?
ex;
var query = from t in context.table1
from a in context.anothertable1.Where(x => t.id == a.id)
select new {a,t};
on line 2, the Where clause .Where(x => t.id == a.id) how would you move it into an expression?
I know i can do this;
Expression<Func<anothertable1, bool>> test = x => x.field1 == 1;
and It would work here;
var query = from t in context.table1
from a in context.anothertable1
.Where(x => t.id == a.id)
.Where(test)
select new {a,t};
and everything work and the sql query generated is as expected.
I can't figure out how to do the same with the other where.
EDIT
a more complex example, i anonymized it so it might not compile
var listOfMinMaxtable1 = (from n in context.table1.Where(table1Filter)
group n by n.table1_Number into grp
select new MinMaxtable1()
{
table1_Id_Max = grp.Max(x => x.table1_Id),
table1_Id_Min = grp.Min(x => x.table1_Id),
table1_Number = grp.Key
});
var listtable2 = (from t in context.table2
group t by t.table2_Id into grp
select new table2()
{
table2 = grp,
table2_Id = grp.Key
});
var query = from MinMax in listOfMinMaxtable1
//inner join **reference 1**
from table3 in context.table3
.Where(x => x.table_Number == MinMax.table_Number)
.Where(noticeMasterFilter) //a working expression<func<>>
//inner join **reference 2**
from Lasttable1 in context.table1
.Where(x => x.table_Id == MinMax.table_Id_Max)
//left join **reference 3**
from Firsttable1 in context.table1
.Where(x => x.table_Id == MinMax.table_Id_Min)
.Where(firstNoticeFilter) //a working expression<func<>>
.DefaultIfEmpty()
//left join **reference 4**
from Lasttable2 in listtable2
.Where(x => x.table_Id == MinMax.table_Id_Max)
.SelectMany(x => x.table2)
.Where(x => x.table2_Id == 123)
.OrderByDescending(x => x.table_Id)
.Take(1)
.DefaultIfEmpty()
if you find //left join reference 3 in the code above
that where clause; .Where(x => x.table_Id == MinMax.table_Id_Min)
might be sometime; .Where(x => x.table_Id == MinMax.table_Id_Max)
I could just copy/paste the whole from and change the where clause while adding noop pattern (an expression that return false and this make entity framework remove the whole thing so it doesn't affect the generated sql/result) with an expression on both from
for reference(this is noise to the question), the noop expression that i'm talking about is;
Expression<Func<table1, bool>> includeFrom= x => false;
and would be used like
//left join **reference 3**
from Firsttable1 in context.table1
.Where(x => x.table_Id == MinMax.table_Id_Min)
.Where(firstNoticeFilter) //a working expression<func<>>
.Where(includeFrom) //<--- this line make it a noop if the expression stay false
.DefaultIfEmpty()
but I don't want to do this if it's possible to make a custom expression that would go into the .Where()
Instead of creating an expression based on one type, you can create a combined type and use that for your where expression.
Two Table Combined Type
public class TwoTableDto
{
public Table1 t { get; set; }
public Table2 a { get; set; }
}
Query without expression
var query = (from t in context.table1
from a in context.anothertable1
select new TwoTableDto { t = t, a = a })
.Where(x => x.t.id == x.a.id);
Expression
Expression<Func<TwoTableDto, bool>> expr = x => x.t.id == x.a.id;
Query with expression
var query = (from t in context.table1
from a in context.anothertable1
select new TwoTableDto { t = t, a = a })
.Where(expr);

how to use Linq " NOT IN"

I'm using Entity Framework
So I want to write a sql command using two tables - tblContractor and tbSiteByCont tables.
It looks like this in SQL
SELECT PKConID, Fname, Lname
FROM tblContractor
WHERE (PKConID NOT IN
(SELECT FKConID
FROM tbSiteByCont
WHERE (FKSiteID = 13)))
but I don't know how to write in Linq.
I tried like this
var query1 = from s in db.tblSiteByConts
where s.FKSiteID == id
select s.FKConID;
var query = from c in db.tblContractors
where c.PKConID != query1.Any()
select Contractor;
But this doesn't work.
So how should I write it? What is the procedure? I'm new to Linq.
var _result = from a in tblContractor
where !(from b in tbSiteByCont
where FKSiteID == 13
select b.FKConID)
.Contains(a.PKConID)
select a;
or
var siteLst = tbSiteByCont.Where(y => y.FKSiteID == 13)
.Select(x => x.FKConID);
var _result = tblContractor.Where(x => !siteLst.Contains(x.PKConID));
I'd use a HashSet, it ensures you only evaluate the sequence once.
var result = from p in tblContractor
let hasht = new HashSet<int>((from b in tbSiteByCont
where b.FKSiteID == 13
select b.PKConID).Distinct())
where !hasht.Contains(p.PKConID)
select p;
may this work too
var _result = from a in tblContractor
.Where(c => tbSiteByCont
.Count(sbc => sbc.FKSiteID == 13 && c.PKConID == sbc.FKConID) == 0)

Categories