3种方式关系:用户,LOB和角色

时间:2011-07-08 15:46:59

标签: .net c#-4.0 entity-framework-4.1 ef-code-first

假设我们有用户,业务线(LOB)和角色。用户有1个LOB。但是用户也可以在不同的LOB中拥有多个角色。

下面的Code First模型创建了3个表USERS,ROLES和LOBS。如果留给他自己的设备,它也会创建UserRoles。这不是我想要的。

到目前为止,我已尝试创建UserLOBRole {RoleId,UserId,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;}
}

1 个答案:

答案 0 :(得分: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; }
}

您的代码可能会抱怨FK,因为EF code first demands navigation property on at least one side of the realation而您的LOBRole目前还没有,所以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;}
}