This is my model classes
public class Serve
{
public int Id { get; set; }
public Table Table { get; set; }
public bool IsFinished { get; set; }
public decimal TotalMoney { get; set; }
public virtual ICollection<Order> Orders { get; set; }
}
public class Order
{
public int Id { get; set; }
public Item Item { get; set; }
public int Numbers { get; set; }
public bool IsCheifReceived { get; set; }
public bool IsCheifCooked { get; set; }
public Serve Serve { get; set; }
public Order()
{
IsCheifCooked = IsCheifReceived = false;
}
}
public class Item
{
public int Id { get; set; }
public string Name { get; set; }
public string Unit { get; set; }
public decimal Price { get; set; }
public Category Category { get; set; }
public bool IsNeedToNotifyChief { get; set; }
}
I want to sum the Number and total money of Orders grouped by same Item (This is the Menu Item of the restaurant).
This is the LINQ query.
var serving = db.Serves
.Where(m => m.Table.Id == table.Id)
.Where(m => m.IsFinished == false)
.OrderByDescending(m => m.Id)
.FirstOrDefault();
var groupedOrder = serving.Orders
.OrderByDescending(m => m.Id)
.GroupBy(m => m.Item)
.Select(g => new
{
Item = g.Key,
Numbers = g.Sum(ri => ri.Numbers)
}).ToList();
But in this case, in .GroupBy(m => m.Item)
the m.Item
is null
, and it grouped all the Orders to one group. (I know the problem is the m.Item
is not loaded in this Query)
Here, I don't know how to make the m.Item is loaded in this LINQ Query. Please help me to do this.
PS: I use Entity Framework 6
I think the variable serving is list of some objects, not a query. If I'm right, you should to include items when you getting serving from DB. It will be look like code below:
var serving = db.Serves
.Include(x => x.Orders)
.Include(x => x.Orders.Select(x => x.Item)) //here you'll get your items
.Where(m => m.Table.Id == ta && m.IsFinished == false)
.OrderByDescending(m => m.Id)
.FirstOfDefault();
//and after that your code should work correctly
if(serving != null) //don't forget check it, if you use FirstOfDefault()
{
var groupedOrder = serving.Orders
.OrderByDescending(m => m.Id)
.GroupBy(m => m.Item)
.Select(g => new
{
Item = g.Key,
Numbers = g.Sum(ri => ri.Numbers)
}).ToList();
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.