【问题标题】:Navigation Property in EF Core is NULLEF Core 中的导航属性为 NULL
【发布时间】:2022-09-23 10:00:01
【问题描述】:

有人可以指导我如何在下表中构建正确的属性导航吗?

我的数据库中有这些表:

然后我需要关联Status 表以获取每个表上的Name 状态

这些是我的模型类:

[Table(\"Companies\")]
public class CompanyEntity
{
    [Key]
    public int Id { get; set; }

    public string Name { get; set; }

    public int Status_Id { get; set; }

    public DateTime Created_Date { get; set; }

    public DateTime Updated_Date { get; set; }

    [ForeignKey(\"Status_Id\")]
    public Status Status { get; set; }
}

[Table(\"Customers\")]
public class CustomerEntity
{
    [Key]
    public int Id { get; set; }

    public string Name { get; set; }
    public int Status_Id { get; set; }

}

[Table(\"Status\")]
public class Status
{
    [Key]
    public int Id { get; set; }

    public string Name { get; set; }

    public Company Company { get; set; }
}

我的目标是当我使用DBContext 获得所有CompaniesCustomers 时,例如var companies = _dbContext.Companies.ToList()。我想获取CompaniesCustomers 的每条记录的状态。我不太确定如何为上述模型正确构建导航属性。

蒂亚!

更新#1

遵循以下建议后,是的,Status 不再是NULL。但是,它得到了错误的状态 ID。它不使用Status_Id,而是使用公司的Id。请参阅下面的 sn-ps。该公司的状态是6

但是,如果您在第二个片段上注意到,状态是3,即公司的Id

我在OnModelCreating 中也有此代码。

            modelBuilder.Entity<Company>()
                .HasOne<Status>()
                .WithMany()
                .HasForeignKey(p => p.Status_Id);

这就是我得到这种行为的原因。但是如果我删除了这个,Status 属性将得到NULL

    标签: c# .net-core entity-framework-core azure-functions


    【解决方案1】:

    您必须添加 .Include() 方法才能在结果中加入您的状态表,如下所示:

    _dbContext.Companies.Include(c =&gt; c.Status).ToList()

    【讨论】:

    • 请在原始问题中查看我的更新。谢谢!
    【解决方案2】:

    刚刚解决了我的问题。我需要将 Company 属性从 public Company Company { get;set; } to public List Companies { get;set; }`

    [Table("Status")]
    public class Status
    {
        [Key]
        public int Id { get; set; }
    
        public string Name { get; set; }
    
        public List<Company> Companies { get; set; }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-10-22
      • 2018-10-10
      • 2020-02-23
      • 1970-01-01
      • 1970-01-01
      • 2015-05-30
      • 1970-01-01
      相关资源
      最近更新 更多