[英]Returning many-to-many results with LINQ in C# asp.net
我正在努力了解LINQ語法以及如何在數據庫中的多對多關系中使用它。 在我的示例項目中,我正在對汽車進行建模和維護,您可以對汽車進行建模。 所以我有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怎么辦?
如果要顯示最新服務:
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();
有很多方法可以做到這一點。 得到您正在談論的內容的幾種可能性(顯示最近日期的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();
這僅取決於您要確切執行的操作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.