Convert SQL into LINQ and Lambda - c#

Please is somebody able to help me convert the following SQL query into LINQ
select p.Description,SUM(s.TotalArea) as TotalArea from Stands s
inner join ContractProducts cp on s.Id = cp.StandId
inner join Products p on cp.ProductId = p.Id
where s.EventId = 1
group by p.Description
Thanks in advance

Maybe something like this:
var result= (
from s in db.Stands
join cp in db.ContractProducts
on s.Id equals cp.StandId
join p in db.Products
on cp.ProductId equals p.Id
where s.EventId == 1
group p by p.Description into g
select new
{
Description=g.Key,
TotalArea = g.Sum (x =>x.TotalArea)
}
).ToList();
Where db is the linqdatacontext

Related

How to translate an SQL query to LINQ

How to translate an SQL query to LINQ
SELECT DISTINCT q.Id
FROM Questions AS q
JOIN TagsQuestions AS tq
ON q.Id = tq.QuestionForeignKey
JOIN Tags AS t
ON t.Id = tq.TagForeignKey
WHERE t.Name IN ('C#', '.Net')
GROUP BY q.Id
HAVING COUNT(*) = 2
Firstly, You should note use DISTINCT q.Id because it's already GROUP BY q.Id.
SELECT q.Id
FROM Questions AS q
JOIN TagsQuestions AS tq ON q.Id = tq.QuestionForeignKey
JOIN Tags AS t ON t.Id = tq.TagForeignKey
WHERE t.Name IN ('C#', '.Net')
GROUP BY q.Id
HAVING COUNT(*) = 2
Secondly, You can transfer from sql to linq syntax like below
var TagNames = new[] {
"C#",
".Net"
};
var result = from q in Questions
join tq in TagsQuestions on q.Id equals tq.QuestionForeignKey
join t in Tags on t.Id equals tq.TagForeignKey
where TagNames.Contains(t.Name)
group q by q.Id into g
where g.Count() = 2
select g.Key;

Need help on Linq-to-SQL query (maybe nested query?)

I am asking for your help regarding a linq query to SQL.
Here is a part of the diagram of my database: https://imgur.com/xFBUm3q
My problem is in the following relationship: tbl_607_bottle and tbl_607_gaz_reporting, I can have several reportings for a bottle but reporting can only have one bottle.
I do this request but it's not satisfying.
var GazReportingWizardViewModel =
(from gr in db.tbl_607_gaz_reporting
join a in db.tbl_607_actors on gr.FK_ID_actors equals a.id
join bo in db.tbl_607_bottle on gr.FK_ID_bottle equals bo.ID
join loc in db.tbl_607_location on bo.FK_ID_location equals loc.ID
join cc in db.tbl_607_conformity_certificate on bo.FK_ID_conformity_certificate equals cc.ID
join j in db.tbl_607_join_bottle_gaz on bo.ID equals j.FK_ID_bottle
join g in db.tbl_607_gaz on j.FK_ID_gaz equals g.ID
join od in db.tbl_607_order_details on g.FK_ID_order_details equals od.ID
where loc.ID == Process
select new GazReportingWizardViewModel
{
bottle_conti_number = bo.bottle_conti_number,
pressure_value = gr.pressure_value,
reporting_date = gr.reporting_date,
first_name = gr.tbl_607_actors.first_name,
last_name = gr.tbl_607_actors.last_name,
expiration_date = cc.expiration_date,
content = od.content_comments
}).Distinct()
.OrderBy(t => t.reporting_date)
.ToList();
I want the last report on each bottle but it return all reports on each bottle.
Would you have an idea of ​​the solution?
Thank you for your time
Thank you so much!
I persisted in trying to solve the problem in a single query when the solution was so simple.
var GazReportingWizardViewModel = (from gr in db.tbl_607_gaz_reporting
join a in db.tbl_607_actors on gr.FK_ID_actors equals a.id
join bo in db.tbl_607_bottle on gr.FK_ID_bottle equals bo.ID
join loc in db.tbl_607_location on bo.FK_ID_location equals loc.ID
join cc in db.tbl_607_conformity_certificate on bo.FK_ID_conformity_certificate equals cc.ID
join j in db.tbl_607_join_bottle_gaz on bo.ID equals j.FK_ID_bottle
join g in db.tbl_607_gaz on j.FK_ID_gaz equals g.ID
join od in db.tbl_607_order_details on g.FK_ID_order_details equals od.ID
where loc.ID == Process
select new GazReportingWizardViewModel
{
bottle_conti_number = bo.bottle_conti_number,
pressure_value = gr.pressure_value,
reporting_date = gr.reporting_date,
first_name = gr.tbl_607_actors.first_name,
last_name = gr.tbl_607_actors.last_name,
expiration_date = cc.expiration_date,
content = od.content_comments
}).ToList();
var res = from element in GazReportingWizardViewModel
group element by element.bottle_conti_number
into groups
select groups.OrderByDescending(p => p.reporting_date).First();

How to write left join, group by and average in c# entity framework Linq

To put it in simple terms i need to write the following SQL in entity framework. I would prefer to do it in Lynq. I'm using mysql
SELECT `p`.`Id`, p.price, p.categoryid, avg(o.rate)
FROM `Product` AS `p`
LEFT JOIN `Order` AS `o` ON `p`.`Id` = `o`.`ProductId`
group by p.id
What I have did so far is below
var data = from p in _context.Product
join o in _context.Order on p.Id equals o.ProductId into orderTemp
from ord in orderTemp.DefaultIfEmpty()
group p by p.Id into gp
select new
{
p.Id,
p.Price,
p.CategoryId,
gp.Average(m => m.Rate)
};
I have been struggling o do this the whole day. Any help would be highly valuable and appreciated. Thank you in advance.
The above is not working, as m is referencing the object of Product.
Thank you everyone who tried to help me out. After a struggle the below worked for me.
var data = from p in _context.Product
join o in _context.Order on p.Id equals o.ProductId into orderTemp
from ord in orderTemp.DefaultIfEmpty()
group ord by p into gp
select new
{
Id = gp.Key.Id,
Price = gp.Key.Price,
CategoryId = gp.Key.CategoryId,
Rate = gp.Average(m => m == null ? 0 : m.Rate)
};
You can try this to find the average from your order table, here the thing is you need select the left outer join result and then do grouping up on it.
(from p in products
join o in Orders on p.id equals o.productId
into pg
from g in pg.DefaultIfEmpty()
select new { p.id, p.categoryId, p.price, g?.rate} into lg
group lg by lg.id into sg
from s in sg
select new { s.id, s.price, rate =sg.Average(r=> r.rate)}).Distinct().ToList();

How to write LINQ left join

var query = from r in db.Resource
join c in db.ResourceProjectedCapacity on r.ID equals c.ResourceID into ps
from c in ps.DefaultIfEmpty(null)
join p in db.Project on c.ProjectID equals p.ID
select new
{
Capacity = c,
Resource = r,
Project = p
};
I have this linq query but it is only returning resources that have a matching row on ResourceProjectedCapacity table. How can I get all resources and in case they dont have a matching record the Capacity object to be null?
from i in db.Resource
let c = db.ResourceProjectedCapacity.Where(cc => i.id == cc.ResourceID).FirstOrDefault()
let p = db.Project.Where(pp => c.ProjectID == pp.ID).FirstOrDefault()
select new
{
Capacity = C,
Resource = i,
Project = p
}
try above code
I think the secondary inner join messes up the left outer join above it. I think a way to work around it is to break the join into a seperate query, and then left join on that, something like this:
var subquery = from c in db.ResourceProjectedCapacity
join p in db.Project on c.ProjectID equals p.ID
select new { c, p };
var query = from r in db.Resource
join c in subquery on r.ID equals c.c.ResourceID into ps
from c in ps.DefaultIfEmpty(null)
select new
{
Capacity = c.c,
Resource = r,
Project = c.p
};
NB don't worry, it won't do two db queries, it'll only execute against your db once you evaluate query with a .ToList() or something like that.

convert this into linq or lambda c#

Can someone please help me convert this SQL to linq or lambda c#
select
count(s.ClassId) [StudentInClass], c.Name [Class], t.Name [teacher]
from
[dbo].[Students] s
inner join
class c on s.ClassId = c.Id
inner join Teacher t
on t.Id = c.TeacherId
group by
s.ClassId, c.Name, t.Name
so far this is what I have, and i am messing it up. I want to achieve the same results as in my sql query
SchoolEntities db = new SchoolEntities();
var StudentsByCourseId = from s in db.Students
join c in db.Classes on s.ClassId equals c.Id
join t in db.Teachers on c.TeacherId equals t.Id
group c by s.ClassId
into g
select g;
in SQL this is what my reults look like, it counts the students in a class by the teacher
StudentCount Class Teacher
1 Geography Teacher1
1 Biology Teacher1
2 Maths Teacher2
You can use an anonymous class to group by multiple properties.
var StudentsByCourseId = from s in db.Students
join c in db.Classes on s.ClassId equals c.Id
join t in db.Teachers on c.TeacherId equals t.Id
group s by new { s.ClassId, Class = c.Name, Teacher = t.Name }
into g
select new
{
StudentInClass = g.Count(),
g.Key.Class,
g.Key.Teacher,
};

Categories