3
B和C之間
public class A  
{ 
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)] 
    public virtual int Aid { get; set; }  

    public virtual ICollection<B> B { get; set; }  
} 


public class B 
{  
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]  
    public virtual int Bid { get; set; } 

    [Key] 
    [Column(Order = 0)] 
    [Required]   
    Public virtual string BName {get ; set} 

    [Key] 
    [Column(Order = 1)] 
    [Required]  
    public virtual int Aid { get; set; } 

    [ForeignKey("Aid")] 
    public virtual A A { get; set; } 

    public virtual ICollection<C> C { get; set; }  
} 


public class C 
{ 
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]  
    public virtual int Cid { get; set; } 

    [Key] 
    [Column(Order = 0)] 
    [Required]  
    Public virtual string CName {get ; set}  

    [Key] 
    [Column(Order = 1)] 
    [Required]   
    public virtual int Bid { get; set; } 

    [ForeignKey("Bid")] 
    public virtual B B { get; set; } 
} 

關係困擾我.I不希望包括如BNAME在C類外鍵映射外鍵在EF代碼第一非主代理鍵柱

錯誤:數在從屬和主要角色的屬性 有關係的約束必須相同

我理解的錯誤,但我想指出C級只能通過投標,我怎麼能實現它,而不會干擾A之間的關係和B.

回答

2

據我的理解是不可能無論使用哪種屬性或流暢API做的EF代碼第一:

但我可以建議你改造一下你的解決方案 - 不要在上創建主鍵- 使其成爲唯一索引 - Unique Key constraints for multiple columns in Entity Framework

public class B 
{  
    [Key] 
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]  
    public virtual int Bid { get; set; } 

    [Index("IX_B_Name_Aid", 1, IsUnique = true)] 
    [Required]   
    Public virtual string BName {get ; set} 

    [Index("IX_B_Name_Aid", 2, IsUnique = true)] 
    [Required]  
    public virtual int Aid { get; set; } 

    [ForeignKey("Aid")] 
    public virtual A A { get; set; } 

    public virtual ICollection<C> C { get; set; }  
} 


public class C 
{ 
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]  
    public virtual int Cid { get; set; } 

    [Key] 
    [Column(Order = 0)] 
    [Required]  
    Public virtual string CName {get ; set}  

    [Key] 
    [Column(Order = 1)] 
    [Required]   
    public virtual int Bid { get; set; } 

    [ForeignKey("Bid")] 
    public virtual B B { get; set; } 
} 

索引會給你同樣的性能優勢的查詢作爲主鍵(雖然有點額外的開銷,以支持主surrogate指數在Bid列)。

另外,推薦閱讀 - Surrogate vs. natural/business keys