C# 如何同时使用两个实体表?

C# 如何同时使用两个实体表?,c#,asp.net-mvc,entity-framework,entity-framework-6,C#,Asp.net Mvc,Entity Framework,Entity Framework 6,我正在做一个学校项目,这个项目是关于展示我学到的一些数据库属性。我有两个实体类,叫做Person和CarInformation。我想一起展示姓名、位置、Person和Brand的天数、CarInformation的PlateNumber 我尝试生成名为的新类,然后将名称、位置、愿望日期、品牌、车牌号分组。在相应的控制器中,我使用Select函数创建了一个列表,但失败 CarInformation实体类 public int Id { get; set; }

我正在做一个学校项目,这个项目是关于展示我学到的一些数据库属性。我有两个实体类,叫做Person和CarInformation。我想一起展示姓名、位置、Person和Brand的天数、CarInformation的PlateNumber

我尝试生成名为的新类,然后将名称、位置、愿望日期、品牌、车牌号分组。在相应的控制器中,我使用Select函数创建了一个列表,但失败

CarInformation实体类

        public int Id { get; set; }             //Primary key of carinfo table

        public string Brand{ get; set; }
        public string PlateNumber { get; set; }
        public int Milage { get; set; }
        public string InsuranceCompany{ get; set; }
        public double ConsumptionPerMile { get; set; }
        public int DailyPrice { get; set; }
        public DateTime AvailableDates { get; set; }

        [ForeignKey("Persons")]                      
        public int OwnerId { get; set; }                //foregein key (Person table to carinfo table)
        public virtual Person Persons { get; set; }     //Navigation property


        public List<Sales> Sales { get; set; }
    public int Id { get; set; }                  //primary key of person table

    public string Name { get; set; }
    public string Location { get; set; }
    public int WishedDays { get; set; }

    public virtual CarInformation Cars { get; set; }     //Navigation property

    public List<CarInformation> cars { get; set; }  //bir insana ait birden fazla araba olabilir

    public List<Sales> sales { get; set; }
相应控制器的索引方法

public ActionResult Index()
    {


        var isimler = db.People.
            Select(i => new Person_CarInformation() { Location=i.Location,Name=i.Name, Brand=i.Cars.Brand,PlateNumber=i.Cars.PlateNumber});


        return View(isimler.ToList());
    }
当我在这种情况下执行时,我得到了这个结果 品牌和车牌号为空

有什么建议吗

多谢各位


您在获取数据时没有包含依赖实体。您可以通过如下所示更改代码来获得它

   var isimler = db.People.Include("Cars").
            Select(i => new Person_CarInformation() { Location=i.Location,Name=i.Name, Brand=i.Cars.Brand,PlateNumber=i.Cars.PlateNumber});

没有错误。我只是无法从CarInformation表中获取姓名和车牌号。您是否已检查外键数据是否正确保存在CarInformation表中?我的CarInformation表在上面。外键是所有者ID。你能给我一个查询表格的例子吗?例如,我只想显示人名和它的汽车。非常感谢。
   var isimler = db.People.Include("Cars").
            Select(i => new Person_CarInformation() { Location=i.Location,Name=i.Name, Brand=i.Cars.Brand,PlateNumber=i.Cars.PlateNumber});