我想要一个lambda表达式,当我从ID为1030的数据库中调用 Company 来带给我公司信息时,该列表包含该公司拥有的所有 car 与每辆汽车相关的所有图像的列表(每辆汽车有4张图像)。
我的课程结构:
public partial class Companies
{
public int CompanyId { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public string Tel { get; set; }
public string Logo { get; set; }
public int? Owner { get; set; }
public int? Address { get; set; }
public int? Publish { get; set; }
public ICollection<Cars> Cars { get; set; }
}
public partial class Cars
{
public int CarId { get; set; }
public string Manufacturer { get; set; }
public string Model { get; set; }
public string Year { get; set; }
public string Description { get; set; }
public decimal? Price { get; set; }
public int? CarCatId { get; set; }
public int? CompanyId { get; set; }
public int? CharacteristicId { get; set; }
public ICollection<CarImages> CarImages { get; set; }
}
public partial class CarImages
{
public int CarImagesId { get; set; }
public string Image { get; set; }
public int? CarId { get; set; }
public Cars Car { get; set; }
}
您可以在 Company 类中看到,我引用了 Cars 类作为ICollection,并且在 Cars 类中使用了相同的内容 CarImages 。
我已经尝试了很多东西,包括:
var compInfo = _context.Companies.SelectMany(cr => cr.Cars.SelectMany(i =>i.CarImages.Where(car => car.CarId == car.Car.CarId))).ToList();
var compInfo2 = _context.Companies.Include(a => a.AddressNavigation).Include(cr =>cr.Cars.).FirstOrDefault(c => c.CompanyId == id);
第二个带给我公司的信息(地址)和汽车列表(成功了一半),但没有图像。
第一个只是给我列出了图像表的所有信息。
答案 0 :(得分:0)
我找到了解决方案。
//Get the Company with id == 1030.
var x = _context.Companies.Include(a => a.AddressNavigation).Include(c => c.Cars).Where(c => c.CompanyId == id).FirstOrDefault();
//Get the Car ICollection and include the CarImages ICollection depending on CompanyID.
var y = _context.Cars.Include(img => img.CarImages).Where(cr => cr.CompanyId == x.CompanyId).ToList();
//Now each Car in our Cars list has a list of CarImages related to each car. Finaly pass our data to our Company var(x) and send it to View.
x.Cars = y;
return View(x);