What would be the Linq expression equivalent of the following TSQL query:
SELECT c.[CustomerId]
,c.[Name]
, (SELECT COUNT(*) FROM Incidents WHERE CustomerId = c.CustomerId) AS IncidentsCount
, (SELECT COUNT(*) FROM Opportunities WHERE CustomerId = c.CustomerId) AS OpportunitiesCount
, (SELECT COUNT(*) FROM Visits WHERE CustomerId = c.CustomerId) AS VisitsCount
FROM [Customers] c
I haven't double-checked this in visual studio but this should work:
var x = (from c in Context.Customers
select new {
CustomerId = c.CustomerId,
Name = c.Name,
IncidentsCount =
Context.Customers.Count(i => i.CustomerId == c.CustomerId),
OpportunitiesCount =
Context.Opportunities.Count(o => o.CustomerId == c.CustomerId),
VisitsCount =
Context.Visits.Count(v => v.CustomerId == c.CustomerId)
});
Update: I changed the code to be a little bit easier to read.
Related
Good day, everyone!
I'm working on a c# test automation script, and I have a sql query that returns a few values based on a few checks with cast, Case When, and Sum - but now we need to transfer it to Entity Framework as a linq query, and I'm not sure how to do so.
Could someone please assist me with this?
Here is my sql query
SELECT
co.orderId AS OrderId
,(SELECT
COUNT(*)
FROM ci_orders (NOLOCK) co
INNER JOIN Customer (NOLOCK) cust
ON cust.IdCustomer = co.customerId
WHERE cust.Email = c.Email
AND co.PaymentTransactionStatusID = 1)
AS CustomerOrdersCount
,co.PitStopStatus AS PitStopStatus
,(SELECT
SUM(ops.Price + ops.QuantityDiscount)
FROM OrderProductSelect (NOLOCK) ops
WHERE ops.OrderId = 2257327)
AS NetPrice
,CAST(CASE WHEN Exists (SELECT
oi.Id
FROM OrderIssues (NOLOCK) oi
LEFT JOIN PitStops ps
ON ps.Id = oi.PitStopId
WHERE oi.OrderId = co.orderId
AND IssueType = 'HighValueOrder') THEN 1
ELSE 0 END AS BIT)
AS IsHighValuePitStop
FROM ci_orders (NOLOCK) co
INNER JOIN Customer (NOLOCK) c
ON c.IdCustomer = co.customerId
WHERE co.orderId =2257327
#eldar - I tried below way
using (var context = GetDbContext())
{
var yellowOrder = context.YellowOrders.FirstOrDefault(x => x.OrderId == orderId);
var result = (from co in context.Orders
join c in context.Customers
on co.customerId equals c.IdCustomer
where co.orderId == orderId
select new
{
OrderId = orderId,
IsHighValuePitStop = (from oi in context.OrderIssues
join ps in context.PitStops
on oi.PitStopId equals ps.Id
where oi.OrderId == orderId && ps.IssueType == "HighValueOrder")
}).Any();
return yellowOrder != null;
}
You can achieve Case When in linq with a ternary (?:) operator. And since your queries are mostly inner selects your linq should look like this :
var result = await (
from co in context.ci_orders
join c in context.Customers on co.customerId eqals c.IdCustomer
where co.orderId =2257327
select new { // here your inner selects go
OrderId = co.orderId,
IsHighValuePitStop = (from oi in context.OrderIssues
join ps in context.PitStops on oi.PitStopId equals ps.Id
where oi.OrderId = co.orderId and oi.IssueType = 'HighValueOrder').Any(), // you could use ternary operator but Any already returns a boolean value ? true : false would be meaningless
NetPrice = context.OrderProductSelect.Where(r=> r.OrderId = 2257327).Sum(ops=> ops.Price + ops.QuantityDiscount),
co.PitStopStatus,
CustomerOrdersCount = (from co in context.ci_orders
join cust context.Customer on co.customerId equals cust.IdCustomer
where cust.Email = c.Email
&& co.PaymentTransactionStatusID = 1
select co).Count()
}).ToArrayAsync()
I want to convert LINQ join to simple SQL inline join query.
This is my LINQ query.
public ProjectTaskList_Deleted GetTaskToBeDeletedByTaskID(int ProjectTaskID)
{
ProjectTaskList_Deleted list=null;
try
{
using (var db = new Cubicle_EntityEntities())
{
list = (from a in db.ProjectTaskList_Deleted where a.ProjectTaskID == ProjectTaskID select a).FirstOrDefault();
}
}
catch (Exception ex)
{
}
return list;
}
This is the equivalent SQL:
select p.ProjectID ProjectID, p.ProjectName + ' - ' + p.ProjectCode as ProjectName
from
Projects p join ProjectTaskLists pl
on p.ProjectID = pl.ProjectID
where pl.IsDeliverable = true and p.CompanyId = #CompanyId
where #CompanyId is a parameter.
This is the SQL Normal query:
select p.ProjectID, p.ProjectName + ' - ' + p.ProjectCode as ProjectName from Projects p
Inner join ProjectTaskLists pl on pl.ProjectID = p.ProjectID
where pl.IsDeliverable == true && p.CompanyId == #CompanyId
I'm having difficulty converting this sql query to a linq query. I'm trying to select all my orders with the order details attached to that order. In sql the query is correct. When I write it in linq is when everything goes haywire. Here is my code:
var result = from order in orders
join orderDetail in orderDetails
on order.OrderID equals orderDetail.OrderID
select new OrderVm
{
OrderId = order.OrderID,
OrderDetails = order.Order_Details.Select(x =>
new OrderDetailVm
{
OrderId = orderDetail.OrderID,
UnitPrice = orderDetail.UnitPrice,
Quantity = orderDetail.Quantity,
ProductId = orderDetail.ProductID
})
};
return result.ToList();
that produces this result
but in sql if I write
select
o.OrderID,
o.CustomerID,
od.UnitPrice,
od.Quantity,
od.productid,
p.ProductName
from Orders o
inner join [Order Details] od
on o.OrderID = od.OrderID
inner join Products p
on p.ProductID = od.ProductID
where o.OrderID = 10248
my expected out come is
It looks like from the way that you are using Order_Details in the nested object that the join already exists and that the join you are using is redundant.
var result = from order in orders
select new OrderVm
{
OrderId = order.OrderID,
OrderDetails = order.Order_Details.Select(x =>
new OrderDetailVm
{
OrderId = x.OrderID,
UnitPrice = x.UnitPrice,
Quantity = x.Quantity,
ProductId = x.ProductID
})
};
i want to translate this SQL query :
SELECT FirstName,LastName, WaiterId, Count(*) AS compte
FROM Waiter
INNER JOIN Client on Waiter.Id = Client.WaiterId
GROUP BY WaiterId,lastname, firstname
ORDER BY compte DESC;
in entity framework.
I tried something like this :
var query = (from w in db.Waiter
join c in db.Client on w.Id equals c.WaiterId
group c by c.WaiterId into g
//orderby
select new
{
WaiterId = g.Key,
count = g.Count()
});
but my select don't work. I can't select FirstName and LastName and i don't even know if my count is good.
You need to include all the properties in the group by.
var query = (from w in db.Waiter
join c in db.Client on w.Id equals c.WaiterId
group c by new { c.FirstName, c.LastName, c.WaiterId} into g
orderby g.Count() descending
select new
{
FirstName = g.Key.FirstName,
LastName = g.Key.LastName,
WaiterId = g.Key.WaiterId,
count = g.Count()
});
I have three tables, Professors, ProfessorStudent, Student.
I want all Professors + How many Students each Professor have.
I can do this:
context.ProfessorSet.Include("Student")
context.ProfessorSet.Include("Student").ToList() will read all three tables.
But i dont wanna get Student table, I want that Linq just get "Professor Table"+ "Count(*) ProfessorStudent Group By StudentId".
Its possible?
I do using this:
var c = from tag in contexto.ProfessorSet
select new
{
Tag = tag,
Count = tag.Student.Count
};
But generate this SQL:
SELECT
C.Id,
C.Nome,
C.C1
FROM
(SELECT
A.Id,
A.Nome,
(SELECT
COUNT(0)
FROM ProfessorStudant AS B
WHERE A.Id = B.ProfessorId
) AS [C1]
FROM Professor AS A)
I want this:
Select A.Id, Count(0) from Professor A
inner join ProfessorStudent B on A.Id = B.ProfessorId
Group By A.Id
from p in context.ProfessorSet
from s in p.Student
group s by s.StudentId into g
select new
{
Professor = p,
StudentCounts = from sc in g
select new
{
StudentId = sc.Key,
Count = sc.Group.Count()
}
}