I've tried to write a LINQ query that will give me all the details in one place, I need the date of production, the employee name and the sum of money this employee should get for his work. this is what I have so far:
var PrePerWorker =
(from Production in context.production
where Production.ProductionDate >= dtpStartDate.SelectedDate && Production.ProductionDate <= dtpEndDate.SelectedDate
select new
{
Worker =
(from Employee in context.employees
where Employee.ID == Production.EmpID
select Employee.FirstName).FirstOrDefault(),
DateOfProduction = Production.ProductionDate,
Total =
Production.Side == 1 ? Production.Amount *
(from Product in context.products
where Product.ProductID == Production.ProductID
select Product.SideA).FirstOrDefault():
Production.Side == 2 ? Production.Amount *
(from Product in context.products
where Product.ProductID == Production.ProductID
select Product.SideB).FirstOrDefault():
Production.Side == 3 ? Production.Amount *
(from Product in context.products
where Product.ProductID == Production.ProductID
select Product.SideC).FirstOrDefault(): 0
}).GroupBy(x => x.DateOfProduction, x => x.Worker);
When I run this and then try to iterate over the results I get an error saying "Specified method is not supported".
Anyone knows why? and how can I fix this?
My guess is that the tertiary ? : operator can't be translated to SQL
For grouping by 2 columns you need GroupBy(x => new {x.DateOfProduction, x.Worker});. And can you explain what you need, because your linq looks like so hard for me.
Related
I have been trying to convert this SQL statement into a linq as i am trying to move the functionality into a program.
Here is the SQL statement
SELECT cust.sg_group_name AS customer,
(SELECT Sum(du.used_space)
FROM sg_groups AS clnt
LEFT JOIN client_disk_usage AS du
ON clnt.sg_group_id = du.sg_group_id
AND clnt.group_role_id = 3
WHERE clnt.parent_group_id = cust.sg_group_id
AND du.day_of_month = 15
AND du.month_of_year = 05
AND du.used_space_year = 2016) AS disk_usage
FROM sg_groups AS cust
WHERE cust.group_role_id = 2
ORDER BY cust.sg_group_name
Essentially the output is just a list with two columns
customer disk_usage
Customer1 136401537652
Customer2 42208008210
If possible i just want to convert this to a linq statement. I have tried putting the query into LinqPad, but it doesn't seem to want to convert from SQL to Linq (just comes up with a blank white page). I have had a crack at the query myself, but i either get something that doesn't work altogether, or an incorrect number of results.
If anyone has any suggestions that would be great!
disk_usage(Sub Query) is a bit Complicated Part. Converted over here. Try this out
var CoreList = (from clnt in EntityName.sg_groups
join du in EntityName.client_disk_usage
on new { GrpId = clnt.sg_group_id, RoleId = clnt.group_role_id } equals new { GrpId = du.sg_group_id, RoleId = 3 } into LJ
from RT in LJ.DefaultIfEmpty()
where du.day_of_month == 15 && du.month_of_year == 05 && du.used_space_year == 2016
select new {clnt, du, RT}
).ToList();
var CoreListSet = CoreList.Select(i=> new YourEntityClass
{
//Fetch the ParentGroupId & UsedSpace
}).ToList();
var CoreListComplete = (from cl in CoreListSet
join cust in EntityName.sg_groups
on cust.sg_group_id equals cl.parent_group_id).ToList();
Now get the sum of CoreListComplete & just implement the base Select Query in Linq!
Apologies for the delayed response. I've marked #Anil answer up as this is the one that helped me find the answer. You solution did work #Sathish but it can be accomplished in a single command. Here is my final solution. Many thanks for your help!
storeGridUsage = (
from cust in db.sg_groups
from client in db.sg_groups
join du in db.client_disk_usage on client.SG_GROUP_ID equals du.SG_GROUP_ID
where client.GROUP_ROLE_ID == 3
where client.PARENT_GROUP_ID == cust.SG_GROUP_ID && du.DAY_OF_MONTH == day && du.MONTH_OF_YEAR == month && du.USED_SPACE_YEAR == year
where cust.GROUP_ROLE_ID == 2
orderby cust.SG_GROUP_NAME
group new {cust, du} by cust.SG_GROUP_NAME
into g
select new StoreGridUsage
{
CustomerName = g.Key,
DiskUsageInBytes = g.Sum(o => o.du.USED_SPACE)
}).ToList();
Can someone please help me convert this query to LINQ as I am new to using Linq which will then be used for google chart information.
Select Question.SubSectionName, SUM(Answers.RatingAnswer) AS Ratings
FROM Question,Answers,Response,Section
Where Answers.QuestionID = Question.QuestionID
AND Answers.ResponseID = Response.ResponseID
AND Question.SectionID=Section.SectionID
AND Section.SectionID = 2
AND Response.ResponseID = #0
AND Question.SubSectionName IS NOT Null
GROUP BY Question.SubSectionName;
What I've got so far :
var submitted = (from ans in db.Answers join ques in db.Questions on
ans.QuestionID equals ques.QuestionID
join resp in db.Responses on ans.ResponseID equals resp.ResponseID
join sec in db.Sections on ques.SectionID equals sec.SectionID
where sec.SectionID == 2 && resp.ResponseID == model.ResponseID
&& ques.SubSectionName!= null
select ques.SubSectionName && ans.RatingAnswer)
Thanks for any help.
Building on your comment this should output a grouping of sums of RatingAnswers:
var submitted =
(from ans in db.Answers
join ques in db.Questions on ans.QuestionId equals ques.QuestionId
join resp in db.Responses on ans.ResponseId equals resp.ResponseId
join sec in db.Sections on ques.SectionId equals sec.SectionId
where sec.SectionId == 2 && resp.ResponseId == model.ResponseID && ques.SubSectionName != null
select new { SubSectionName = ques.SubSectionName, RatingAnswer = ans.RatingAnswer })
.GroupBy(a => a.SubSectionName)
.Select(a => new { SectionName = a.Key, Sum = a.Sum(s => s.RatingAnswer) });
There may be a more efficient way of writing this.
I would also point out that to me the data structure seems flawed. That is, it seems either normalized incompletely or improperly. That's certainly for you to work out on your own.
Linqer helps you to convert SQL to LINQ.
If you want to get better in LINQ, I recommend using LINQPad. However, LINQPad can't convert from SQL to LINQ but from LINQ to SQL.
try this-
from q in Question
join a in Answers on q.QuestionID equals a.QuestionID
join r in Response on r.ResponseID equals a.ResponseID
join s in Section on s.SectionID equals q.SectionID
where s.SectionID= 2 and r.ResponseID= #0 and q.SubSectionName!=null
Group by q.SubSectionName
I have 2 tables (table Mngr and VWE) I want my query returns the table Mngr records in whichw.Mdl and o.CM are equal (all the models that are equal) but the o.cv does not exist in table VWE.
can anybody help me writing it?
table Mngr table VWE
------------ -----------
CM CV Mdl Vrs
a 5 a 1
b 2
a 3
HERE: I want it to return the row in table Mngr with CM a and CV 5, because the version 5 is new
would you please help me how can I write in using Linq?
var q = (from o in Mngr
from v in VWE
.Where(w=>
w.Mdl == o.CM &&
w.Vrs != o.CV)
where o.Mod == 1
select o).distinct();
THANKS
You should check if none matching records exist in VME set:
Mngr.Where(m => m.Mod == 1 && !VME.Any(v => v.Mdl == m.CM && v.Vrs == m.CV))
Query syntax
from m in Mngr
where m.Mod == 1 !VME.Any(v => v.Mdl == m.CM && v.Vrs == m.CV)
select m
Try this query
from s in context.Mngr
where !context.VWE.Any(es=>(es.mdl==s.cm)&&(es.vrs==s.vc))
select s;
This should work for you, considering
o.cv does not exist in table VWE
var query = Mngr.Where(m => VWE.Any(v => v.Mdl == m.CM) &&
!VWE.Any(v => v.Vrs == m.CV));
I am having following linq -
var quantity = (from p in context.StoreInventory
where p.BookId== BookId
&& p.StoreAddress == StoreAddress
select p).Sum(i => i.Quantity);
I am getting error -
The method 'Sum' is not supported
Can anyone tell me the reason and required changes.
var quantity = (from p in context.StoreInventory
where p.BookId== BookId
&& p.StoreAddress == StoreAddress
select p.Quantity).Sum();
This should work - the sum is performed on 'Quality' column, which is taken using select statement. That's because Sum(expression) is not supported by LINQ to Entities, but standard Sum() is.
Whole work should be done by database, so no rows will be retrieved by application - just single number.
Use Enumerable.ToList before you call Sum to convert the query to collection.
var quantity = (from p in context.StoreInventory
where p.BookId== BookId
&& p.StoreAddress == StoreAddress
select p).ToList().Sum(i => i.Quantity);
Edit: This will bring all the row and will apply the sum which is not efficient way of doing. As you need to sum up quantity you can select quanity instead of row.
var quantity = (from p in context.StoreInventory
where p.BookId== BookId
&& p.StoreAddress == StoreAddress
select p.Quantity).Sum();
I'm trying to rewrite a SQL query in LINQ to Entities. I'm using LINQPad with a typed datacontext from my own assembly to test things out.
The SQL query I'm trying to rewrite:
SELECT DISTINCT variantID AS setID, option_value AS name, option_value_description AS description, sort_order as sortOrder
FROM all_products_option_names AS lst
WHERE lst.optionID=14 AND lst.productID IN (SELECT productID FROM all_products_option_names
WHERE optionID=7 AND option_value IN (SELECT name FROM brands
WHERE brandID=1))
ORDER BY sortOrder;
The LINQ to Entities query I've come up with so far (which doesn't work due to a timeout error):
from a in all_products_option_names
where a.optionID == 14 && all_products_option_names.Any(x => x.productID == a.productID && x.optionID == 7 && brands.Any(y => y.name == x.option_value && y.brandID == 1))
select new
{
id = a.variantID,
name = a.option_value,
description = a.option_value_description,
sortOrder = a.sort_order,
}
This is the error I get when I run the above query: An error occurred while executing the command definition. See the inner exception for details.
And the inner exception is: Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding.
Edit:
I use MySQL and probably that's why LINQPad doesn't show me the generated SQL.
The SQL version doesn't time out.
Edit 2:
I solved the problem by completely changing the query, so this question is irrelevant now.
I marked Steven's response as the correct one, because he was closest to what i was trying to achieve and his response gave me the idea which led me to the solution.
Try this:
var brandNames =
from brand in db.Brands
where brand.ID == 1
select name;
var brandProductNames =
from p in db.all_products_option_names
where p.optionID == 7
where brandNames.Contains(p.option_value)
select p.productId;
var results =
from p in db.all_products_option_names
where p.optionID == 14
where brandProductNames.Contains(p.productId)
select new
{
setID = p.variantID,
name = p.option_value,
description = p.option_value_description,
sortOrder = p.sort_order
};
I would recommend doing joins rather than sub-select's as you have them. Sub-selects are not very efficient when you look at performance, it's like having loops inside of loops when you code , not a good idea. This could actually cause that timeout your getting if your database is running slowly even thou that looks like a simple query.
I would try using joins with a distinct at the end like this:
var results =
(from p in db.all_products_option_names
join p2 in db.all_products_option_names on p.productId equals p2.productId
join b in db.Brands on p2.option_value equals b.name
where p.optionID == 14
where p2.optionID == 7
where b.BrandID == 1
select new
{
setID = p.variantID,
name = p.option_value,
description = p.option_value_description,
sortOrder = p.sort_order
}).Distinct();
Or you could try using joins with the into and with an any like so
var results =
from p in db.all_products_option_names
join p2 in (from p3 in db.all_products_option_names.Where(x => x.optionId == 7)
join b in db.Brands.Where(x => x.BrandID == 1) on p3.option_value equals b.name
select p3) into pg
where p.optionID == 14
where pg.Any()
select new
{
setID = p.variantID,
name = p.option_value,
description = p.option_value_description,
sortOrder = p.sort_order
};