2017-05-24 147 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