【发布时间】: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
但显然我错过了一些东西。任何帮助都非常感谢,因为这应该是一件容易的事,但我显然无法做到。
【问题讨论】:
-
你能显示你的 linq 查询吗?
-
是的,做到了。谢谢
标签: entity-framework .net-core