LINQ multiple joins with a Group By not Working - c#

After trying a lot i couldn't get this to work
I have below query:
var query = from citiez in db.cities
join site in db.sites on citiez.city_id equals site.city_id
join ords in db.orders on site.site_id equals ords.site_id
group site by site.site_id into grouped
select new {
sit = grouped.Count(),
cits = grouped.FirstOrDefault().orders
.Where(o => o.site.city.city_name == city)
};
var list = query.ToList();
It works fine but gives Circular reference error.
I have searched it but couldn't get this to work in my case
What i am trying to do in SQL is:
SELECT s.site_id, COUNT(o.order_id) TotalOrders
FROM city c
INNER JOIN site s ON c.city_id = s.city_id
INNER JOIN dbo.[order] o ON s.site_id = o.site_id
WHERE c.city_id = 4
GROUP BY s.site_id
The Query returns the desired result in SSMS.
EDIT
This is my Controller Action code:
public ActionResult draw_chart(string city)
{
var query = from citiez in db.cities
join site in db.sites on citiez.city_id equals site.city_id
join ords in db.orders on site.site_id equals ords.site_id
group site by site.site_id into grouped
select new
{
sit = grouped.Count(),
cits = grouped.FirstOrDefault().orders
.Where(o => o.site.city.city_name == city)
};
var list = query.ToList();
return Json(list, JsonRequestBehavior.AllowGet);
}
Any help would be much Appreciated.

Try this one your controller action. you will get site id and orders for site
public ActionResult draw_chart(string city)
{
var query = from citiez in db.cities
join site in db.sites on citiez.city_id equals site.city_id
join ords in db.orders on site.site_id equals ords.site_id
where citiez.city_name == city
group site by site.site_id into grouped
select new
{
siteId = grouped.Key,
ordersforsite = grouped.Count(),
};
var list = query.ToList();
return Json(list, JsonRequestBehavior.AllowGet);
}

That Linq doesn't look like the SQL you showed and most of the time you don't need to use JOIN (provided you have a good database design with relations setup). Based on your SQL you can use a Link query like this:
var result = db.Orders
.Where(o => o.City_id == 4)
.GroupBy(o => o.Site.Site_id)
.Select(g => new {
Site_id = g.Key,
TotalOrders = g.Count
});

What you intend can be expressed in this query:
var query = from citiez in db.cities
where citiez.city == city
from site in citiez.sites
select new {
sit = site.orders.count,
cits = site.orders
};
That would give you the orders for each site.

Related

SQL Server query to C# Linq

I'm currently having a rough time converting my SQL query to LINQ for a school project I'm using WPF and Entity Framework
here is my SQL query (working exactly as I expect)
select IngrediantName,sum(IngrediantQuantity) as Quantity, IngrediantMeasurementUnit from Users
join Shopping_List
on Users.UserID = Shopping_List.ShoppingListID
join List_Item
on List_Item.ShoppingListID = Shopping_List.ShoppingListID
join Ingrediant
on Ingrediant.IngrediantID = List_Item.IngrediantID
where Users.UserID = 1
group by IngrediantName,IngrediantMeasurementUnit
Here is the query that I have so far
var query = from user in dbContext.Users
join shoppingList in dbContext.ShoppingLists on user.UserId equals shoppingList.UserId
join listItem in dbContext.ListItems on shoppingList.ShoppingListId equals listItem.ShoppingListId
join ingrediant in dbContext.Ingrediants on listItem.IngrediantId equals ingrediant.IngrediantId
where currentUserNumber == user.UserId
select new
{
name = ingrediant.IngrediantName,
quantity = ingrediant.IngrediantQuantity,
unit = ingrediant.IngrediantMeasurementUnit,
};
Here is what i try so far
var query = from user in dbContext.Users
join shoppingList in dbContext.ShoppingLists on user.UserId equals shoppingList.UserId
join listItem in dbContext.ListItems on shoppingList.ShoppingListId equals listItem.ShoppingListId
join ingrediant in dbContext.Ingrediants on listItem.IngrediantId equals ingrediant.IngrediantId
where currentUserNumber == user.UserId
group ingrediant by ingrediant.IngrediantQuantity into x
select new
{
name = x.GroupBy(x => x.IngrediantName),
quantity = x.Sum(x => x.IngrediantQuantity),
unit = x.GroupBy(x => x.IngrediantMeasurementUnit),
};
this one return the following error wiches doesn't tell much
Argument type 'System.Linq.IQueryable1[System.Linq.IGrouping2[System.String,Microsoft.EntityFrameworkCore.Query.TransparentIdentifierFactory+TransparentIdentifier2[Microsoft.EntityFrameworkCore.Query.TransparentIdentifierFactory+TransparentIdentifier2
If someone could point me in the right direction I would appreciate it, if you need more info I will provide it for sure
Thanks
UPDATE
I got this working here the answers to the question for anyone else
var query =
from user in dbContext.Users
join shoppingList in dbContext.ShoppingLists
on user.UserId equals shoppingList.UserId
join listItem in dbContext.ListItems
on shoppingList.ShoppingListId equals listItem.ShoppingListId
join ingrediant in dbContext.Ingrediants
on listItem.IngrediantId equals ingrediant.IngrediantId
where currentUserNumber == user.UserId
group ingrediant by new { name = ingrediant.IngrediantName, unit = ingrediant.IngrediantMeasurementUnit } into x
select new
{
name = x.Key.name,
quantity = x.Sum(x => x.IngrediantQuantity),
unit = x.Key.unit,
};
if you look at the group line
group ingrediant by new { name = ingrediant.IngrediantName, unit = ingrediant.IngrediantMeasurementUnit } into x
from my understanding you use the new to create a new selector then you can use x.key.name and x.key.unit where name and unit are simply some variable

Linq - Linq expression different context error

I have 3 tables
- ERPEntry
- ERPEntryType
- ERPApp
I am trying to get data from these 3 tables using the below query but i got the error :
specified linq expression contains references to queries that are
associated with different contexts
var erpEntryInfo = (from s in ERPDB.ERPEntrys
JOIN t in ERPDB.ERPEntryTypes
on s.EntryTypeID equals t.EntryTypeID
join a in APPDB.ERPApps
on s.AppId equals a.AppId
where s.UserIDAdded == '250176'
select new ERPInfo
{
EntryId = s.EntryID,
EntryType = t.EntryTypeName,
ERPApp = a.ApplicationName,
DateAdded = s.DateAdded
}).OrderByDescending(d => d.DateAdded).Take(10).ToList();
I searched based on the errror and tried to split the above query into 2 as below.
var res = (from s in ERPDB.ERPEntrys
join t in ERPDB.ERPEntryTypes
on s.EntryTypeID equals t.EntryTypeID
where s.UserIDAdded == '250176'
select new {s.EntryTypeID, s.DateAdded, t.EntryTypeName, s.AppID }).OrderByDescending(d => d.DateAdded).Take(10).ToArray();
var y = (from a in APPDB.ERPApps
join b in res on a.AppId equals //??//
select new ERPInfo
{
EntryId = b.EntryID,
EntryType = b.EntryTypeName,
ERPApp = a.ApplicationName,
DateAdded = b.DateAdded
}).ToList();
I am having an issue in the above query to access AppId which i got into the result res..i commented with //??// in the above code
can i get any help on this.

MVC 5 select from 2 model linq expression

For example i have 2 model.
ASpnetUserRoles and ASPnetRoles
i want to select ASPnetRoles.Name,ASPnetROles.ID where ASPnetRoles.ID in ASPnetUserRoles.
i only know how to write in SQL
select * from modalA where modelA.id in(select modelB.id from modelB)
if you enable "Lazy Loading" , you can use this linq query :
using(var db = ..."context"..)
{
var q = db.AspNetUserRoles.where(c=>c.UserID = userIdVal)
.select(z=> new { RoleId = z.RoleId
,userId = z.UserId
,RoleName = z.AspNetRole.RoleName
})
.toList();
}
This is what i did eventually.
IEnumerable<IdentityRole> ro;
ro = (from p in haha join ur in aspNetUser.AspNetRoles on p.Id equals ur.Id select p);
Here a generic sample you must create a class (no EF), and store the result to it.
IQueryable<ResultClass> result=from t1 in db.Table1
join t2 in db.Table2
//Here the relation fields
on t1.IdTable1 equals t2.IdTable2
//Here where conditios and/or orderby
select new ResultClass()
{
Field1=t1.SomeField,
Field2=t2.SomeField,
//all need fields
}
Use the result
result.ToList()

Instead of FirstOrDefault() what do I use to get all values in group by?

How can I get all the values of SpecificationDetails_ID.By the below code I just get the first value form a group of values.What to do to get all values?
using(APM context=new APM())
{
var lstprodspc = (from s in context.M_ProductSpecifaction
//join p in context.M_SpecificationDetails on s.SpecificationDetails_ID equals p.ID
// join r in context.M_Specifications on p.Specification_ID equals r.ID
where s.Product_ID == P_ID
group s by s.Parent_ID into pg
select new
{
ProductSD_ID = pg.FirstOrDefault().SpecificationDetails_ID
}).ToList();
}
From the above code I just get 34,31,31,31,26,26,26,26.
You can project it using Select like this:-
select new
{
Parent_ID = pg.Key,
ProductSD_ID = pg.Select(x => x.SpecificationDetails_ID).ToList()
}).ToList();

Converting SQL to LINQ query when I cannot use "IN"

I'm trying to convert this very simple piece of SQL to LINQ:
select * from Projects p
inner join Documents d
on p.ProjectID = d.ProjectID
left join Revisions r
on r.DocumentID = d.DocumentID
and r.RevisionID IN (SELECT max(r2.RevisionID) FROM Revisions r2 GROUP BY r2.DocumentID)
WHERE p.ProjectID = 21 -- Query string in code
This says, if any revisions exist for a document, return me the highest revision ID. As it's a left join, if not revisions exist, I still want the results returned.
This works as expected, any revisions which exist are shown (and the highest revision ID is returned) and so are all documents without any revisions.
When trying to write this using LINQ, I only get results where revisions exist for a document.
Here is my attempt so far:
var query = from p in db.Projects
join d in db.Documents on new { ProjectID = p.ProjectID } equals new { ProjectID = Convert.ToInt32(d.ProjectID) }
join r in db.Revisions on new { DocumentID = d.DocumentID } equals new { DocumentID = Convert.ToInt32(r.DocumentID) } into r_join
from r in r_join.DefaultIfEmpty()
where
(from r2 in db.Revisions
group r2 by new { r2.DocumentID }
into g
select new { MaxRevisionID = g.Max(x => x.RevisionID) }).Contains(
new { MaxRevisionID = r.RevisionID }) &&
p.ProjectID == Convert.ToInt32(Request.QueryString["projectId"])
select new { d.DocumentID, d.DocumentNumber, d.DocumentTitle, RevisionNumber = r.RevisionNumber ?? "<No rev>", Status = r.DocumentStatuse == null ? "<Not set>" : r.DocumentStatuse.Status };
I'm not very good at LINQ and have been using the converter "Linqer" to help me out, but when trying I get the following message:
"SQL cannot be converted to LINQ: Only "=" operator in JOIN expression
can be used. "IN" operator cannot be converted."
You'll see I have .DefaultIfEmpty() on the revisions table. If I remove the where ( piece of code which does the grouping, I get the desired results whether or not a revision exists for a document or not. But the where clause should return the highest revision number for a document IF there is a link, if not I still want to return all the other data. Unlike my SQL code, this doesn't happen. It only ever returns me data where there is a link to the revisions table.
I hope that makes a little bit of sense. The group by code is what is messing up my result set. Regardless if there is a link to the revisions table, I still want my results returned. Please help!
Thanks.
=======
The code I am now using thanks to Gert.
var query = from p in db.Projects
from d in p.Documents
where p.ProjectID == Convert.ToInt32(Request.QueryString["projectId"])
select new
{
p.ProjectID,
d.DocumentNumber,
d.DocumentID,
d.DocumentTitle,
Status = d.Revisions
.OrderByDescending(rn => rn.RevisionID)
.FirstOrDefault().DocumentStatuse.Status,
RevisionNumber = d.Revisions
.OrderByDescending(rn => rn.RevisionID)
.FirstOrDefault().RevisionNumber
};
gvDocumentSelection.DataSource = query;
gvDocumentSelection.DataBind();
Although this works, you'll see I'm selecting two fields from the revisions table by running the same code, but selecting two different fields. I'm guessing there is a better, more efficient way to do this? Ideally I would like to join on the revisions table in case I need to access more fields, but then I'm left with the same grouping problem again.
Status = d.Revisions
.OrderByDescending(rn => rn.RevisionID)
.FirstOrDefault().DocumentStatuse.Status,
RevisionNumber = d.Revisions
.OrderByDescending(rn => rn.RevisionID)
.FirstOrDefault().RevisionNumber
Final working code:
var query = from p in db.Projects
from d in p.Documents
where p.ProjectID == Convert.ToInt32(Request.QueryString["projectId"])
select new
{
p.ProjectID,
d.DocumentNumber,
d.DocumentID,
d.DocumentTitle,
LastRevision = d.Revisions
.OrderByDescending(rn => rn.RevisionID)
.FirstOrDefault()
};
var results = from x in query
select
new
{
x.ProjectID,
x.DocumentNumber,
x.DocumentID,
x.DocumentTitle,
x.LastRevision.RevisionNumber,
x.LastRevision.DocumentStatuse.Status
};
gvDocumentSelection.DataSource = results;
gvDocumentSelection.DataBind();
If you've got 1:n navigation properties there is a much simpler (and recommended) way to achieve this:
from p in db.Projects
from d in p.Documents
select new { p, d,
LastRevision = d.Revisions
.OrderByDescending(r => r.RevisionId)
.FirstOrDefault() }
Without navigation properties it is similar:
from p in db.Projects
join d in db.Documents on new { ProjectID = p.ProjectID }
equals new { ProjectID = Convert.ToInt32(d.ProjectID) }
select new { p, d,
LastRevision = db.Revisions
.Where(r => d.DocumentID = Convert.ToInt32(r.DocumentID))
.OrderByDescending(r => r.RevisionId)
.FirstOrDefault() }
Edit
You can amend this very wide base query with all kinds of projections, like:
from x in query select new { x.p.ProjectName,
x.d.DocumentName,
x.LastRevision.DocumentStatus.Status,
x.LastRevision.FieldA,
x.LastRevision.FieldB
}

Categories

Resources