sql query do in subquery in LINQ - c#

below is my SQL query
SELECT
p.Name
, p.DisplayName
, (
SELECT COUNT(*)
FROM LicenseActivations la
WHERE la.ProductId=p.Id
AND la.AccountId='QWNjb3VudDo2N2YyMTcwMC0xMWZlLTExZWItYjNkMS0yN2U1Mjk0MGVhYmU='
) AS COUNT
FROM [Products] p
GROUP BY p.Name, p.DisplayName, p.id;
here I am using two tables 1.Products 2.LicenseActivations, I need to form LINQ, Can anyone help me out with this one

In Linq you seldom need joins. With a proper database design with relations established, Linq navigation properties does the job (which are generated automatically by the tools for you):
var list = from p in _DbContext.Products
select new {
p.Name,
p.DisplayName,
Count = p.LicenseActivations.Count(x => x.AccountId=="QWNjb3VudDo2N2YyMTcwMC0xMWZlLTExZWItYjNkMS0yN2U1Mjk0MGVhYmU=")
};
is the corresponding Linq query of your SQL (ToList() is optional).
EDIT: If you don't have proper relations in your database, then:
var list = from p in _DbContext.Products
select new {
p.Name,
p.DisplayName,
Count = _DbContext.LicenseActivations
.Count(x => x.ProductId == p.Id &&
x.AccountId=="QWNjb3VudDo2N2YyMTcwMC0xMWZlLTExZWItYjNkMS0yN2U1Mjk0MGVhYmU=")
};

Related

Linq query for top parents by number of childs, including this number

In my model, there are entities Article and Tag in many-to-many relation through table ArticleTag.
I want to select "trending tags" - tags with most articles in last X days, and I want this count too.
Basically, I need help creating EF Linq query equivalent to this SQL query, with ideal result being Dictionary<Tag, int>
SELECT TOP 50
t.Id, t.Name, count(*)
FROM ArticleTag at
JOIN Article a ON a.Id = at.ArticleId
JOIN Tag t ON t.Id = at.TagId
WHERE a.DateCreated > '2019-10-01'
GROUP BY t.Id, t.Name
ORDER BY count(*) DESC
Can this be done without having ArticleTag as DbSet in DbContext (since it is not really an entity, and I dont need it besides this query).
You have to use navigation properties for this query and do not need to know anything about ArticleTag table.
var query =
from a in ctx.Articles
from t in a.Tags
where a.DateCreated > someDate
group t by new { t.Id, t.Name } into g
orderby g.Count() descending
select new
{
g.Key.Id,
g.Key.Name,
Count = g.Count()
};
var result = query
.Take(50)
.ToDictionary(x => new Tag { Id = x.Id, Name = x.Name }, x => x.Count);

Linq Query Group By Multiple Columns Having Count > 1

I have a query I know how to do in SQL but struggling to figure out the LINQ query. Here is the SQL.
SELECT ordNo, tranNo, COUNT(distinct custNo)
FROM orders
GROUP BY ordNo, tranNo
HAVING COUNT(distinct custNo) > 1
I don't feel like this is the same question that I see you marked as a duplicate. The linked question only groups on a single property. I've lost track of the Linq queries I've tried but here is one.
var countList = from o in orders
group o by new {o.orderNo, o.tranNo, o.custNo}
into grp
where grp.Key.custNo.Distinct().Count() > 1
select grp;
I tried the suggestion below but like someone commented you can't access the custNo property.
Just spitballing since I don't know the table structure.
context.orders
.GroupBy(o => new { o.ordNo, o.tranNo, o.custNo })
.Where(o => o.custNo.Distinct().Count() > 1)
.Select(o => new {
ordNo = o.ordNo,
tranNo = o.tranNo
});

Replacing SQL join and group query with linq query in Entity Framework

I have an existing SQL query:
select
mn.accountid, sum(u.peak), sum(u.text), sum(u.datagig),
sum(p.minutesallowed), sum(p.messagesallowed), sum(p.dataallowed)
from
usage u
inner join
mtn mn on u.mtnid = mn.Id
inner join
[plan] p on p.id = mn.planid
group by
mn.accountid
Using Entity Framework, I'm working on converting this to linq, and I've gotten this far:
var tots = from u in currentUsage
join mn in mtns on u.mtnId equals mn.Id
join p in plans on mn.PlanId equals p.Id
group u by u.AccountId into g
select new MainUsageResults
{
TotalPeakMinutes = g.Sum(x => x.Peak),
TotalData = g.Sum(x => x.DataGig),
TotalMessaging = g.Sum(x => x.Text),
TotalAllowedMinutes = g.Sum(x => ???) ,
TotalAllowedMessages = g.Sum(x => ???) ,
TotalAllowedData = g.Sum(x => ???)
};
I can't figure out how to sum up the data that is on the joined tables. In SQL one would have the whole set of columns available in a join, but it doesn't seem to be the case here. How do I get the sum of the columns on the joined tables in this example?
Thanks to #3-14159265358979323846264, a real nice example can be found here

want to convert SQL query to LINQ query in E.F

I am developing app with MVC 3.5 and EF.
I have written the SQL query and I want to rewrite in the LINQ, but I don't know how to use it...
here is the sql query
select * from PurchaseOrders where CreatedById in
(select Employees_Id from EmployeeRole where Roles_Id in
(select Roles_Id from EmployeeRole where Employees_Id = 17))
Assuming:-
your context is set up correctly and you have all the navigation
properties in place
your query is "Get me all of the purcahse orders
created by any employee who shares a role with employee #17"
You can use:-
context.Employees.Where(x => x.Id == 17)
.SelectMany(x => x.Roles)
.SelectMany(x => x.Employees)
.Distinct()
.SelectMany(x => x.PurchaseOrders);
Assuming that your above query is just a bit weird and you actually meant to do:
SELECT * FROM PurchaseOrders WHERE CreatedById = 17;
Your LINQ query would be:
PurchaseOrders.Where(Order => Order.CreatedById = 17);
or
var Orders = from Order in PurchaseOrders
where Order.CreatedById = 17
select Order;
Seeing your update I guess you would actually be better off selecting you employee and then all of the purchase orders i.e.
var Orders = Employees.Single(x => x.Id == 17).PurchaseOrders;
but beware above will work only if there is such an employee
var s= (from po in _db.PurchaseOrders
join er in _db.EmployeeRoles on po.CreatedById equals er.Employees_Id
let _ser in _db.EmployeeRoles.Where(c=>c.Employees_Id == 17)
where _ser.Select(c=>c.Roles_Id).contails(er.Roles_Id)
Select po).toList();

Equivalent LINQ to SQL code

Am new to this here is my T-SQL
SELECT category.id, category.name,COUNT(job.id) AS countofjobs
FROM category
LEFT OUTER JOIN job ON category.id = job.categoryid AND job.active=1
WHERE category.featured=1
GROUP BY category.id, category.name
ORDER BY category.name
what will be the equivalent LINQ to SQL code? any help will be appreciated
Sorry I forgot to mention that there is no relationship database side, tables have no association at all defined in db, thats the main issue, this is really just sample sql to see how I can write Link to SQL for T-SQL that requires: Left outer join, Count of outer join table records and sorting
var result = dataContext.Categories
.Where(c => c.Featured)
.OrderBy(c => c.Name)
.Select(c => new { c.Id,
c.Name,
CountOfJobs = c.Jobs.Count(j => j.Active) };
Alternatively:
var result = from c in dataContext.Categories
where c.Featured
orderby c.Name
select new { c.Id, c.Name, CountOfJobs = c.Jobs.Count(j => j.Active) };
Since you don't have relationships:
var result = from c in dataContext.Categories
where c.Featured
orderby c.Name
select new {
c.Id,
c.Name,
CountOfJobs = dataContext.Jobs.Count(j => j.categoryId == c.Id && j.Active)
};

Categories