【问题标题】:Call ICollection in ICollection with Lambda Expression使用 Lambda 表达式在 ICollection 中调用 ICollection
【发布时间】:2019-08-20 22:29:16
【问题描述】:

我想要一个 lambda 表达式,当我从 id 为 1030 的数据库中调用 Company 以向我提供公司信息时,该列表包含该公司拥有的所有 汽车 和与每辆车相关的所有图像的列表(每辆车有 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 类中也有相同的引用汽车图像

我尝试了很多东西,包括那些:

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);

第二个给我带来了公司信息(以及地址)和汽车清单(成功了一半),但没有图像..

第一个只是给我列出了图像表的所有信息。

【问题讨论】:

  • 不要发布文字图片。请编辑您的问题以改用实际文本。只需将代码直接复制粘贴到问题中即可。

标签: c# asp.net-mvc lambda


【解决方案1】:

我找到了解决方案。

//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);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-04-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多