我很难理解LINQ语法以及如何在数据库中使用它与多对多关系。在我的示例项目中,我正在为汽车建模汽车和维护。所以我有3张桌子:
在网站上,我显示了所有这3个表中的信息,因此我创建了一个视图模型CarsIndexViewModel来保存Car及其关联的CarServices。
public class Car
{
public int Id { get; set; }
[Required]
[StringLength(40)]
public string Name { get; set; }
[Required]
[Range(1900, 2018)]
public int Year { get; set; }
public string Make { get; set; }
public string Model { get; set; }
public string Color { get; set; }
public int Mileage { get; set; }
public virtual ICollection<CarService> CarServices { get; set; }
}
public class Service
{
public int Id { get; set; }
public string Name { get; set; }
public virtual ICollection<CarService> CarServices { get; set; }
}
public class CarService
{
public int Id { get; set; }
public int CarId { get; set; }
[Required]
[Display(Name = "Service")]
public int ServiceId { get; set; }
[Required]
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}")]
[Display(Name = "Date of Service")]
public DateTime ServiceDate { get; set; }
[Column(TypeName = "Money")]
public decimal? Cost { get; set; }
public bool HasReceipt { get; set; }
[Required]
[Display(Name = "Mileage At Time of Service")]
public int Mileage { get; set; }
public virtual Car Car { get; set; }
public virtual Service Service { get; set; }
}
和视图模型:
public class CarsIndexViewModel
{
public Car Car { get; set; }
public IEnumerable<CarService> Services { get; set; }
}
我已经能够在我的控制器中使用此代码返回所有服务及其信息:
var query = (
from car in _context.Cars
select new CarsIndexViewModel()
{
Car = car,
Services = car.CarServices
}).ToList();
return View(query);
我无法弄清楚的是如何只返回符合特定条件的CarServices。例如,如果我只想从最近的日期显示CarServices怎么办?
答案 0 :(得分:1)
如果您想展示最新服务:
var query = (from car in _context.Cars
select new CarsIndexViewModel()
{
Car = car,
Services = car.CarServices
.OrderByDescending(cs => cs.ServiceDate)
.Take(5) // only 5 most recent
.ToList()
}).ToList();
答案 1 :(得分:0)
有很多方法可以做到这一点。获得你所谈论的几种可能性(从最近的日期开始显示CarServices)是这样的:
上次n
近期服务:
var n = 4;
var query = (
from car in _context.Cars
select new CarsIndexViewModel()
{
Car = car,
AllServices = car.CarServices,
RecentServices = car.CarServices.OrderBy(x => ServiceDate).Take(n)
}).ToList();
指定日期之后的最近服务:
var recentThreshold = new DateTime(2017,01,01);
var query = (
from car in _context.Cars
select new CarsIndexViewModel()
{
Car = car,
AllServices = car.CarServices,
RecentServices = car.CarServices.Where(x => ServiceDate > recentThreshhold)
}).ToList();
所有服务最后一天都发生的最近服务:
var latestServiceDates = (
from car in _context.Cars
select new KeyValuePair<int, DateTime>()
{
Key = car.id,
Value = car.CarServices.OrderByDescending(x => ServiceDate).First()
}).ToList();
var query = (
from car in _context.Cars
select new CarsIndexViewModel()
{
Car = car,
AllServices = car.CarServices,
RecentServices = car.CarServices.Where(x => ServiceDate = latestServiceDates.First(y => y.Key == x.id))
}).ToList();
这完全取决于你要做的事情。