[英]how to write this LINQ query of 3 tables?
Table1 CAR (CARID, CarModelID ,CARuniqueinfo1, CARUniqueinfo2): contians all cars have been entered to the warehouse. 表1 CAR(CARID,CarModelID,CARuniqueinfo1,CARUniqueinfo2):表示已将所有汽车输入仓库。
Table2 CarModel (CarModelID ,Modelinfo1 ,Modelinfo2 ) 表2 CarModel(CarModelID,Modelinfo1,Modelinfo2)
Table3 Sale (SaleID, CarID, clientID, EmpID) 表3销售(SaleID,CarID,clientID,EmpID)
What is the Linq Query that returns : 返回的Linq查询是什么:
number of sold cars only for ModelID=101 仅ModelID = 101的售出汽车数量
DataClassesDataContext db = new DataClassesDataContext();
Simple Way: 简单方法:
var result =
db.Sale
.GroupBy(item => item.CarId)
.Select(item => new { item.Key, item.Count() });
Nice way: 好方法:
var result =
from sale in db.Sale
join car in db.CAR
on car.CARID equals sale.CarID
join carModel in db.CarModel
on carModel.CarModelID equals car.CarModelID
select new
{
Model = carModel,
SoldCars = db.Sale.Count(item => item.CarID == car.CARID)
};
Assuming you have a navigation propertiy for Sale(CarID)
: 假设您有一个用于
Sale(CarID)
的导航属性:
int all = db.Models
.Where(m => m.Cars.SelectMany(c => c.Sales).Any())
.Select(m => new {m.ModelID, m.Cars.Count}).ToArray();
var counts = Model.GroupBy(m => m.CarModelID)
.Select(grp => ModelId = grp.Key, Count = grp.Count())
This: 这个:
Dictionary<int, int> carsSold = new Dictionary<int, int>();
foreach (Car in Cars) {
carrsold.Add(x => x.Id, Sales.Where(y => y.CarId == x.Id).Count());
}
will leave you with a dictionary that maps car id to amount sold. 将为您提供一本词典,该词典将汽车ID映射到已售出的金额。
carsSold[1]
would return amount sold by the car with id of 1. carsSold[1]
将返回ID为1的汽车的销售金额。
private int GetCarsSoldCount(int modelId)
{
return db.Sale.Count(x => x.CarID == modelId);
}
var r = from car in CarTable
from sale in SalesTable
where sale.CarID == car.CarID
group sale by car.CarModelID into g
select new { Model = g.Key, Count = g.Count() };
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.