开发者

Best approach for association between three tables with Entity Framework

开发者 https://www.devze.com 2023-04-04 02:08 出处:网络
First, sorry for my english. Second, I\'m not good at database modeling, so I might be completely wrong.

First, sorry for my english. Second, I'm not good at database modeling, so I might be completely wrong.

I'm writing a website (think of it as a forum), where in every post, each user can have a different roles.

The way I would do it without using entity framework is creating 3 tables:

Where UserGroupRole would contain the keys for the 3 tables.

How can I do it with entity framework?

Maybe the whole aproach is incorrect, I'm not sure.

Thanks in advance!


Yes, I would probably also work with 4 entities and tables. In EF 4.1 something along these lines:

public class User
{
    public int Id { get; set; }
    public ICollection<UserGroupRole> UserGroupRoles { get; set; }
}

public class Group
{
    public int Id { get; set; }
    public ICollection<UserGroupRole> UserGroupRoles { get; set; }
}

public class Role
{
    public int Id { get; set; }
    public ICollection<UserGroupRole> UserGroupRoles { get; set; }
}

public class UserGroupRole
{
    [Key]
    public int UserId { get; set; }   // FK property
    [Key]
    public int GroupId { get; set; }  // FK property
    [Key]
    public int RoleId { get; set; }   // FK property

    public User User { get; set; }
    public Group Group { get; set; }
    public Role Role { get; set; }
}

The foreign key properties enforce all three relationships to be required (null is not allowed) and the complex key over all three Ids ensure that any combination of user, group and role can only exist once. You can remove some of the navigation collections - for example in Group and Role - if you don't need them.

0

精彩评论

暂无评论...
验证码 换一张
取 消