EF Core 一对多包括

我在我的数据库中使用 EF-CORE 在 ASP.NET Core MVC 网站上工作。

我有一张Doc桌子和一张Signature桌子:

  • 一个人Doc可以有很多Signatures

  • 一个Signature只能上Doc

这是我的代码优先实体模型:

文件

public class Doc

{

    [Key]

    public int DocID { get; set; }


    [Required]

    public int DocTypeID { get; set; }

    [ForeignKey("DocTypeID")]

    public virtual DocType DocType { get; set; }


    [Required]

    public int Version { get; set; }


    [Required]

    public Byte[] Data { get; set; }


    [ForeignKey("DocID")]

    public List<Signature> Signatures { get; set; }

}

签名

public class Signature

{

    //FK ITPolicyVersion

    [Key]

    public int DocID { get; set; }

    [ForeignKey("DocID")]

    public virtual Doc Doc { get; set; }


    //FK EmployeeID

    [Key]

    public int EmployeeID { get; set; }

    [ForeignKey("EmployeeID")]

    public virtual Employee Employee { get; set; }


    [Required]

    [DataType(DataType.Date)]

    [DisplayFormat(DataFormatString = "{0:dd-MM-yyyy}", ApplyFormatInEditMode = true)]

    [Display(Name = "Signature Date")]

    public DateTime? SignatureDate { get; set; }


    public String Value { get; set; }

}

但是当我使用这个请求时:


_applicationDBContext.Doc

    .Include(d => d.DocType)

    .Include(d => d.Signatures)

    .OrderBy(d => d.DocType)

    .ToList();

d.Signatures 始终为空,我不知道为什么。


这是我在 SQL 中尝试执行的操作:


SELECT * FROM Doc d

JOIN DocType dt ON dt.DocTypeID = d.DocTypeID

JOIN Signature s ON s.DocID = d.DocID

JOIN Employee e ON e.EmployeeID = s.EmployeeID

这在 SQL 中运行良好,但不适用于 LINQ


幕布斯7119047
浏览 169回答 3
3回答

慕码人2483693

在您的 DbContext 的 OnModelCreating 中,您是否放置了 Doc 和 Signature 的关系?像这样:modelBuilder.Entity<Signature>().HasOne(m&nbsp;=>&nbsp;m.Doc).WithMany(m&nbsp;=>&nbsp;m.Signature).HasForeignKey(m&nbsp;=>&nbsp;m.DocID);
打开App,查看更多内容
随时随地看视频慕课网APP