2017-05-24 148 views
1

我有以下型号EF 6映射复杂的组合键

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; } 
} 

我怎么会映射这些模型之间的关系,具体来说,我无法弄清楚如何定义在杂志模式组合键映射到帐户通过CompanyId,ACCOUNTID

回答

1

你可以用流利的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; } 
} 
+0

完美的......我不知道为什么我找不到这一点,它的那么简单...... – user1979215