我正在尝试获取每个城市的总销售数量,并在DataGrid中显示结果。到目前为止,我失去了更多的头发而不是取得了进步。我是LINQ的新手,我可能一无所知。这就是我所拥有的:
var sales = from sale in db.SalesOrderHeaders
join cust in db.Customers on sale.CustomerID equals cust.CustomerID
join cad in db.CustomerAddresses on cust.CustomerID equals cad.CustomerID
join ad in db.Addresses on cad.AddressID equals ad.AddressID
group sale.TotalDue by ad.City into g
select new { City = ad.City, Sales = g.Sum() };
这是dbml。它的TotalDue列我试着按地址表中的City进行求和。
会欣赏任何意见!
答案 0 :(得分:2)
我认为您需要使用City = g.Key
代替City = ad.City
但您很可能根本不需要使用join
语法,因为您已经在数据库中设置了关系。您只需使用对象上的导航属性
var sales = from ad in db.Addresses
from cad in ad.CustomerAddresses
from sale in cad.Customer.SalesOrderHeaders
group sale.TotalDue by ad.City into g
select new
{
City = g.Key,
Sales = g.Sum()
};
我认为你想按CustomerAddress
分组,也许你想使用ShipToAddress
或BillToAddress
?
答案 1 :(得分:1)
您不需要连接,因为您可以使用导航属性,并且可以在另一端开始查询:
DialogResult.Cancel
导航属性不显示在dbml图中,但它们存在于c#类中。
如果您想要特定地址类型的总和,可以添加where子句(from address in db.Address
select new
{
City = address.City,
Sales = (from ca in address.CustomerAddresses
// where ca.AddressType == someVariable
from soh in ca.Customer.SalesOrderHeaders
select soh.TotalDue).Sum()
}
)。