首先从数据库映射一对多代码

map one to many code first from database

我在映射 salesheader 和 saleslines 之间的一对多关系时遇到问题。我首先使用 entity framework 6.1 和流利 api 数据库中的代码。一个销售主管可以有多个销售线。

SalesHeader PK 是文档类型和否

SalesLine PK 是单据号和行号和单据类型

SalesLine中的Document No是SalesHeader中的外键

 modelBuilder.Entity<SalesLine>()
            .HasRequired<SalesHeader>(s => s.SalesHeader)
            .WithMany(s => s.SalesLines)
            .HasForeignKey(s => new { s.Document_No_, s.Line_No_, s.Document_Type });

public partial class SalesHeader
{
    [Key]
    [Column("Document Type", Order = 0)]
    [DatabaseGenerated(DatabaseGeneratedOption.None)]
    public int Document_Type { get; set; }

    [Key]
    [Column(Order = 1)]
    [StringLength(20)]
    public string No_ { get; set; }

    [Column("Sell-to Customer No_")]
    [Required]
    [StringLength(20)]
    public string Sell_to_Customer_No_ { get; set; }

    public virtual ICollection<SalesLine> SalesLines { get; set; }



}
public partial class SalesLine
{
    [Key]
    [Column("Document Type", Order = 0)]
    [DatabaseGenerated(DatabaseGeneratedOption.None)]
    public int Document_Type { get; set; }

    [Key]
    [Column("Document No_", Order = 1)]
    [StringLength(20)]
    public string Document_No_ { get; set; }

    [Key]
    [Column("Line No_", Order = 2)]
    [DatabaseGenerated(DatabaseGeneratedOption.None)]
    public int Line_No_ { get; set; }

    [Required]
    [StringLength(20)]
    public string No_ { get; set; }

    public virtual SalesHeader SalesHeader { get; set; }


}

要使用数据注释来做到这一点,请将其包含在您的 SalesLine class:

[Key, ForeignKey("SalesHeader")]
[Column("Document Type", Order = 0)]
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public int Document_Type { get; set; }

[Key, ForeignKey("SalesHeader")]
[Column("Document No_", Order = 1)]
[StringLength(20)]
public string Document_No_ { get; set; }