【问题标题】:How to use 2 entity tables together?如何同时使用 2 个实体表?
【发布时间】:2019-04-18 00:39:19
【问题描述】:

我正在做一个学校项目,该项目是关于显示我学到的一些数据库属性。我有 2 个实体类,称为 Person 和 CarInformation。我想一起显示来自 Person 和 Brand 的 Name、Location、WhishedDays 和来自 CarInformation 的 PlateNumber。

我尝试生成一个名为的新类,然后我将名称、位置、WishedDays、Brand、PlateNumber 分组。在相应的控制器中,我用 Select 函数创建了一个列表,但失败了。

汽车信息实体类

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

Person-CarInformation 类



 public string Name { get; set; }
 public string Location { get; set; }
 public int WishedDays { get; set; }
 public string Brand { get; set; }
 public string PlateNumber { 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());
    }

当我在这种情况下执行时,我得到了这个结果 Brand 和 PlateNumber 为空。

有什么建议吗?

谢谢。

https://imgur.com/D9a8whD

【问题讨论】:

    标签: c# asp.net-mvc entity-framework entity-framework-6


    【解决方案1】:

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

       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 表中获取 Name 和 PlateNumber。 imgur.com/pPeNQav
    • 您是否检查过CarInformation 表中的外键数据是否正确保存?
    • 我的 CarInformation 表在上面。外键是 OwnerId。你能给我一个关于我的表的示例查询吗?例如,我只想显示人名及其汽车。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-12-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多