2011-07-08 20 views
1

比方說,我們有用戶,行當(LOB)和角色。用戶有1個LOB。但是用戶也可以在不同的LOB中擁有多個角色。3雙向關係:用戶,LOB和角色

下面的代碼首先模型創建3代表用戶,角色和LOBS。如果留給他自己的設備,它也會創建UserRoles。這不是我想要的。

到目前爲止,我已經嘗試創建UserLOBRole {角色ID,用戶ID,LOBCode}對象並標記各個領域爲複合主,但EF約吠叫外鍵。

有什麼辦法,我可以在EF 4.1代碼首先描述這種關係?

任何幫助,非常感謝。

public class User 
{ 
    public int UserId {get;set;} 
    public string UserName {get;set;} 
    public virtual LOB UserLOB {get;set;} 

    // HOW DO I DEFINE RELATIONSHIP HERE? 
    public virtual ICollection<Role> UserRoles {get;set;} 

} 

public class Role 
{ 
    public int RoleId {get;set;} 
    public string RoleName {get;set;} 
} 

public class LOB 
{ 
    public string LOBCode {get;set;} 
    public string LobName {get;set;} 
} 

回答

0

這是不可能的,而不通過這個新的實體暴露UserLOBRole作爲單獨的實體和互連UserRole和LOB。隱藏結表僅適用於許多一對多的關係,沒有任何額外的數據,但不是這種情況。

public class UserLOBRole 
{ 
    [Key, Column(Order = 0)] 
    public int UserId { get; set; } 
    [Key, Column(Order = 1)] 
    public int RoleId { get; set; } 
    [Key, Column(Order = 2)] 
    public string LOBCode { get; set; } 

    public virtual User User { get; set; } 
    public virtual Role Role { get; set; } 
    [ForeignKey("LOBCode")] 
    public virtual LOB LOB { get; set; } 
} 

您的代碼可能會抱怨,因爲FKS和EF code first demands navigation property on at least one side of the realationLOBRole目前還沒有這麼UserLOBRole必須有他們。

而且你User現在將使用:

public class User 
{ 
    public int UserId {get;set;} 
    public string UserName {get;set;} 
    public virtual LOB UserLOB {get;set;} 

    public virtual ICollection<UserLOBRole> UserRoles {get;set;} 
} 
+0

謝謝,看起來這是唯一的出路。需要擦亮API來回答諸如「什麼樣的角色該用戶是否擁有」 quesions,「該用戶是否擁有在吊射作用」等。 – b0rg