EF 6 映射复杂复合键

EF 6 Mapping Complex Composite Keys

我有以下型号

public class Company
{
    [Key, Column(Order=0)]
    public int Id {get;set;}
    public string CompanyCode { get; set; }
    public string Name { get; set; }

    public virtual ICollection<Account> Accounts { get; set; }
    public virtual ICollection<Journal> Journals { get; set; }

}

public class Account
{
    [Key, Column(Order=0)]
    public int Id { get; set; }

    [Key, Column(Order=1), ForeignKey("Company")]
    public int CompanyId { get; set; }

    public int GLAccountNumber { get; set; }
    public decimal Balance { get; set; }

    public virtual Company Company { get; set; }
    public virtual ICollection<Journal> Journals { get; set; }
}

public class Journal
{
    [Key, Column(Order=0)]
    public int Id { get; set; }

    [Key, Column(Order=1), ForeignKey("Company")]
    public int CompanyId { get; set; }

    [ForeignKey("Account")]
    public int AccountId { get; set; }

    public DateTime EntryDate { get; set; }
    public decimal Amount { get; set; }

    public virtual Company Company { get; set; }
    public virtual Account Account { get; set; }
}

我将如何映射这些模型之间的关系,具体来说,我不知道如何在 Journal 模型中定义 Composite Key 以通过 CompanyId、AccountId 映射到 Account

你可以使用 fluent APi(我个人的偏好 - 清晰且不易出错):

modelBuilder.Entity<Journal>()
    .HasRequired(e => e.Account)
    .WithMany(e => e.Journals)
    .HasForeignKey(e => new { e.AccountId, e.CompanyId });

但如果您更喜欢数据注释,请在 导航 属性 上应用 ForeignKey 属性并指定 FK 属性的逗号分隔列表:

public class Journal
{
    [Key, Column(Order=0)]
    public int Id { get; set; }

    [Key, Column(Order=1)]
    public int CompanyId { get; set; }

    public int AccountId { get; set; }

    public DateTime EntryDate { get; set; }
    public decimal Amount { get; set; }

    [ForeignKey("CompanyId")]
    public virtual Company Company { get; set; }

    [ForeignKey("AccountId,CompanyId")]
    public virtual Account Account { get; set; }
}