How to convert this Sql query to LINQ query - sql

can any one to help to convert this below given sql query to linq.
exec sp_executesql N'use db;
WITH Members AS
(
select ROW_NUMBER() OVER (ORDER BY id DESC) as row, num
from tbl
)
Select row, num
from Members
where row BETWEEN #InitialRow AND #EndRow order by row ASC;',N'#InitialRow int,#EndRow int',#InitialRow=0,#EndRow=5
--
thanks,

Here is a way to to it (with #InitialRow=0,#EndRow=5) :
var result = Members
.OrderByDescending(x => x.id)
.Take(5)
.Select((x,i) =>
new { row = i, num = x.num });
With any values:
var result = Members
.OrderByDescending(x => x.id)
.Skip(InitialRow)
.Take(EndRow-InitialRow)
.Select((x,i) =>
new { row = i+InitialRow, num = x.num });

Related

SELECT and SUM in Entity Framework

I want to sum all the columns and where context between dates, basically I want to convert the below SQL query to EF:
select meterCategory, sum(cost) maxCost
from [dbo].[UsageData]
where date between '2019-06-25' and '2019-06-25' and
cost >= 1
group by meterCategory
order by maxCost desc
(var startDate, var endDate) = (new DateTime(2019, 6, 25), new DateTime(2019, 6, 25));
var result =
await dbContext.UsageDatas
.Where(ud => ud.Cost >= 1 && ud.Date >= startDate && ud.Date <= endDate)
.GroupBy(ud => ud.MeterCategory)
.Select(g => new { MeterCategory = g.Key, MaxCost = g.Sum(c => c.Cost) })
.OrderByDescending(g => g.MaxCost)
.ToListAsync();
You can also use tuples and even name their properties, instead of anonymous classes.
Or since you're SQL oriented, you might want to use C# LINQ query syntax (this one uses tuple):
var query =
from ud in dbContext.UsageDatas
where ud.Cost >= 1 && ud.Date >= startDate && ud.Date <= endDate
group ud by ud.MeterCategory into g
select (MeterCategory: g.Key, MaxCost: g.Sum(ud => ud.Cost)) into r
orderby r.MaxCost descending
select r;
var result = await query.ToListAsync();

select some ids from sql in linq

hi I'm using the query below to select studentId and Score from table1 now i want select users that i selected their ids from table2, how i can select it with ids?
i can select users with this query from v in dc.tbl_Students select v but i want select some users that i have their id.
var qBestMan = (from T in (((from tbl_ActPoints in dc.tbl_ActPoints
select new
{
StudentId = (int?)tbl_ActPoints.StudentId,
Score = (int?)tbl_ActPoints.Score
}).Concat(
from tbl_EvaPoints in dc.tbl_EvaPoints
select new
{
StudentId = (int?)tbl_EvaPoints.StudentId,
Score = (int?)tbl_EvaPoints.Score
})))
group T by new
{
T.StudentId
} into g
orderby g.Sum(p => p.Score) descending
select new
{
g.Key.StudentId,
HighScoreUser = g.Sum(p => p.Score)
}).ToArray();
Try something like this:
//qBestMan must be a List, or a IEnumarable and not a Array. Remove the .ToArray() at the end, or substitute it by .ToList()
var Result = from users in dc.tbl_Students
join bestMen in qBestMan on bestMen.StudentId equals users.userid
select new
{
//fields that you want
example = users.example,
other = bestMen.other
};

Query syntax in entity framework

I'm doing a query (see below), but I do not know how to retrieve all data from a select.
var model = new dbContext();
var query = from mp in model.matiere_premiere join req in (from stk in model.stock_mp
join ms in model.matiere_premiere
on stk.matiere_premiere_code equals
ms.code
where stk.date <= DateTime.Today
orderby stk.date descending
select new new { stk.qte, stk.matiere_premiere_code })
on mp.code equals req.matiere_premiere_code
group mp by new { mp.code } into grp
orderby grp.Key
select new
{
grp.Key,
grp.First().designation,
grp.Last().frns
};
The equivalent sql query is:
SELECT matiere_premiere.code,matiere_premiere.designation,
"matiere_premiere.unite, matiere_premiere.frns ,IF(ISNULL(REQ.qte), '0.00', REQ.qte) AS qte
FROM matiere_premiere LEFT JOIN (SELECT qte,matiere_premiere_code FROM stock_mp
JOIN matiere_premiere ON matiere_premiere.code = matiere_premiere_code
WHERE DATE <= CURRENT_DATE() ORDER BY DATE DESC)
AS REQ ON REQ.matiere_premiere_code = matiere_premiere.code
GROUP BY matiere_premiere.code ORDER BY matiere_premiere.code
it's simple, the group is also an enumerator, so you should return
select grp;
then, for each group, you can do a foreach of the values
foreach(var group in query)
{
Console.WriteLine("Key: " + group.Key);
foreach(var v in group)
{
Console.WriteLine("Value: " + v.Property);
}
}

Nhibernate Queryover with subquery get Next free number

How can I do this in nHibernate using queryover :
SELECT MIN(t.subid)+1 AS NextID
FROM subject t
WHERE NOT EXISTS
(SELECT id FROM subject n WHERE n.subid=t.subid+1)
Currently I have this but its not working because of this statement "SubId+1"
_session.QueryOver(() => subject)
.WithSubquery
.WhereNotExists(
subject
.Where(x => x.SubId==SubId+1)
.Select(x => x.Id)
)
.Select(Projections.ProjectionList()
.Add(Projections.Min<subject>(x => x.SubId)))
.List().First()
One way, using NOT IN instead of NOT EXISTS (results are the same) would be like this (the SQL query would be a bit different, but result will be the same)
Subjectsubject = null;
Subjectinner = null;
var subquery = QueryOver.Of<Subject>(() => inner)
.Select(Projections.SqlProjection(
// important the subid is the column name, not property name
" subid - 1 as innerId" // the trick here is, that we compare
, new[] { "innerId" } // inner ID - 1, with outer ID
, new IType[] { NHibernateUtil.Int32 }))
;
var id = session.QueryOver(() => subject)
.WithSubquery
.WhereProperty(() => subject.ID)
.NotIn(subquery)
.Select(Projections.ProjectionList().Add(Projections.Min<Subject>(s => s.ID)))
.SingleOrDefault<int>();
var id = id + 1 ; // here we increment in C#, instead of projecting that into SQL
Summary: not sure about algorithm you've used, but the trick how to get "subid - 1" is to use projection:
Projections.SqlProjection(
" subid - 1 as innerId" // sql statement
, new[] { "innerId" } // its alias
, new IType[] { NHibernateUtil.Int32 }) // type is int
NOTE: I would expect the last Projections to be MAX

Linq to Entities simple group query

How to write (simple) LINQ to Entities query that groups elements by some attribut and count them?
SELECT answernumber, count(answerID) FROM answers
WHERE questionID = id
GROUB BY answernumber
ORDERBY answernumber;
That should be simple but i don't know how to write it.
var query = answers
.GroupBy(a => a.answernumber, a => a, (k, g) => new {answernumber = k, Count = g.Count()})
.OrderyBy(i => i.answernumber);
Or the other way:
var query2 = from a in answers
group a by a. answernumber into g
orderby g.Key
select new { answernumber = g.Key, Count = g.Count() };