【问题标题】:One-to-Many EF .NET Core Relationship Not Working一对多 EF .NET Core 关系不起作用
【发布时间】:2020-05-27 17:55:22
【问题描述】:

我有一个 .net 核心 api 应用程序,其中包括 EF 来检索数据。我已经设置了一个数据上下文,并且可以很好地映射数据库中的表。当我尝试建立关系时,尽管我总是得到嵌套对象的空值。

我有一个“机会”类,其中包含一个 ICollection 的“笔记”

public class Opportunity
{
    public int Id { get; set; }
    public string Name { get; set; }
    ...
    public decimal FinalDealProfit { get; set; }
    public ICollection<CRMNote> CRMNotes { get; set; }
}

还有一个引用机会的 Note 类:

public class CRMNote
{
    public int Id { get; set; }
    public int OpportunityId { get; set; }
    public string Note { get; set; }
    public string User { get; set; }
    public DateTime DateTime { get; set; }
    public string FilePath { get; set; }
    public Opportunity Opportunity { get; set; }
}

在我的上下文类中有以下设置:

modelBuilder.Entity<Opportunity>(entity =>
  {
    entity.ToTable("CRM_Opportunity");
    entity.HasMany<CRMNote>(n => n.CRMNotes)
      .WithOne(t => t.Opportunity)
      .HasForeignKey(k => k.OpportunityId);
    });

我也一直在映射 Note 类:

modelBuilder.Entity<CRMNote>(entity =>
  {
    entity.ToTable("CRM_Note");
    //entity.HasOne<Opportunity>(t => t.Opportunity)
    //    .WithMany(p => p.CRMNotes)
    //    .HasForeignKey(k => k.OpportunityId);
  });

如您所见,我一直在研究如何将实体连接在一起。

每当我检索到机会时,尽管 notes 数组始终为空。我尝试在 Opportunity 类上放置一个空的构造函数:

public Opportunity()
  {
    CRMNotes = new List<CRMNote>();
  }

但这只是意味着我得到一个空数组而不是 null。

我看不到我错过了什么。我已经检查了它的文档:

https://www.entityframeworktutorial.net/efcore/one-to-many-conventions-entity-framework-core.aspx

但显然我错过了一些东西。任何帮助都非常感谢,因为这应该是一件容易的事,但我显然无法做到。

【问题讨论】:

标签: entity-framework .net-core


【解决方案1】:

有三种常见的 O/RM 模式用于加载相关数据 急于加载, 显式加载 和 延迟加载

例如,在急切加载中,您可以使用:

var opportunities=context.opportunities.Include(opportunity=>opportunity.CRMNotes).ToList()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-09-17
    • 2017-10-26
    • 2021-09-15
    • 1970-01-01
    • 2021-05-20
    • 2021-10-11
    • 1970-01-01
    相关资源
    最近更新 更多