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();
Related
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=")
};
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);
I have a trouble with converting this SQL query to Entity Framework:
SELECT Products.Name, COUNT(*)
FROM OrdersProducts
JOIN Products on OrdersProducts.ProductId = Products.Id
GROUP BY Products.Id
ORDER BY COUNT(*) DESC
Tried hard but with no results. I don't have any idea how to make it work.
If your entity model relations allows it, you could try something like that :
dbcontext.Products
.Include(orders=> orders.OrderProducts)
.Select(x => new { Name = x.Name, Count = x.OrderProducts.Count })
.OrderByDescending(x => x.Count)
.ToList();
I think the SQL generated by EF could be near of your query...
i'm starter in linq, i have write this T-SQL Query
select * from DOCUMENT_TYPES where document_id in(
select document_id from Clearance_Document where Clearance_id=(select clearance_id from clearance_id from request where request_id=3))
i want convert this T-SQL Query to linq, please help me, thanks
Well, I would start first by refactoring your SQL into something other than a chain of nested sub-queries. I think this ought to do the same thing, and it's much more readable:
SELECT
*
FROM
DOCUMENT_TYPES dt
JOIN
Clearance_Document cd
ON
dt.document_id = cd.document_id
JOIN
Request r
ON
cd.clearance_id = r.clearance_id
WHERE
r.request_id = 3
(I'm assuming that from clearance_id from request was a typo.)
Then you can easily refactor into a LINQ statement:
var result = from dt in DOCUMENT_TYPES
join cd in Clearance_Document on dt.document_id equals cd.document_id
join r in Request on cd.clearance_id equals r.clearance_id
where r.request_id = 3
select new {
property1 = dt.something,
property2 = cd.somethingElse,
...
};
var result =
from a in DOCUMENT_TYPES
let list =
(
from b in Clearance_Document
where b.Clearance_id == (from c in clearance_id where request_id == 3).First<string>())
select b
).ToList()
where list.Contains(a.document_id)
select a;
Something like that should do (i guessed you're using EF, but you can easyly adapt to other LinQ-Types):
context.Document_Types.Where(doc =>
conext.Clearance_Document.Where(cd =>
cd.Clearance_Id == context.Request.Single(r => r.Request_Id == 3)
).Contains(doc.Document_Id)
).ToList();
How about
var result = c.Id context.Request.Single(r => r.Id == 3)
.Clearances.SelectMany(c => x.DocumentTypes);
In effect, get the one and only Request with an Id equal to 3, then get all the DocumentTypes of all its Clearances.
If your database is set up with the appropriate foreign keys these relationships will be automatically generated as part of your model.
I am having trouble trying to convert the following query from SQL to Linq, in particular with the having count and group by parts of the query:
select ProjectID
from ProjectAssociation
where TeamID in ( select TeamID
from [User]
where UserID in (4))
group by ProjectID
having COUNT(TeamID) = (select distinct COUNT(TeamID)
from [User]
where UserID in (4))
Any advice on how to do so would be much appreciated.
var groups = from pa in ProjectAssociation
let teamIds = User.Where(u => u.UserID == 4).Select(u => u.TeamID)
where teamIds.Contains(pa.TeamID)
group pa by pa.ProjectID;
var result = from g in groups
let count = User.Where(u => u.UserID == 4).Select(u => u.TeamID).Distinct().Count()
where g.Count() == count
select g.Key;
Or maybe more optimal:
var teamIds = User.Where(u => u.UserID == 4).Select(u => u.TeamID).AsEnumerable();
var groups = ProjectAssociation.Where(pa => teamIds.Contains(pa.TeamID)
.GroupBy(pa => pa.ProjectID);
var result = from g in groups
let count = teamIds.Distinct().Count()
where g.Count() == count
select g.Key;
By the way, i think that by
select distinct COUNT(TeamID)
you meant:
select COUNT(distinct TeamID)
There is a tool (cheap) that will convert queries like this for you. It's called Linqer. I own a copy and have found that it's able to convert event the most complex of queries. The URL is http://www.sqltolinq.com/
It's not free, but it's pretty inexpensive and has a 30 day trial.