首页 > 解决方案 > 如何从依赖于实体框架核心中另一个表的表中获取记录?

问题描述

我想从依赖于三个表的数据库中获取一些记录。三张表是:

1.Company(Id,Name)
2. Car(Id,CompanyId,Name)
3. Showroom(Id,CarId,Name)

现在一家公司包含许多汽车,许多陈列室中可能存在许多汽车。我想从公司'2'汽车与汽车一起存在的陈列室表中获取记录。是否可以在实体框架核心中做到这一点?

标签: c#entity-frameworkentity-framework-core

解决方案


我认为您的实体将是:

公司

 public class Company
 {
    public int Id {get; set;}
    public string Name {get; set;}

    public ICollection<Car> Cars {get; set;}
  }

车:

public class Car
   {
        public int Id{get; set;}
        public string Name {get; set;}
        public int CompanyId{get; set;}
        public Company Company {get; set;}

      }

陈列室:

public class ShowRoom
     {
        public int Id{get; set;}
        public string Name {get; set;}
        public int CarId{get; set;}
        public Car Car{get; set;}

      }

在你的方法中:

var context = new SomeContext();



 var showRooms= context.ShowRooms
                    .Include(x=> x.Car)
                    .ThenInclude(x=> x.Company)
                    .Where(x=> x.Car.Company.Id== 2)
                    .ToList();

推荐阅读