How can I get a list of linked 1-n elements?

2019-08-30 05:31发布

That's my basic (Database First) diagram on SQL Server:

enter image description here

When I Update Model from Database using Entity Framework (6.x) within my MVC application, I expect Users got this property:

public virtual ICollection<Role> Roles { get; set; }

As well Roles with:

public virtual ICollection<User> Users { get; set; }

But instead I got:

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

Where am I wrong?

1条回答
男人必须洒脱
2楼-- · 2019-08-30 06:04

Your design is wrong.

Many-to-many relation is defined by a table, which consist only of two IDs of considerated tables, which togeteher form composite key. You have almost this design, but you have additional primary key to "relation" table, which ruins everything :)

If you use this code to generate your tables, you'll get correct relations:

create table users(
    userid int identity(1,1) primary key,
    --other columns
    username varchar(10)
)
create table roles(
    roleid int identity(1,1) primary key,
    rolename varchar(10)
)
create table usersroles(
    userid int foreign key references users(userid),
    roleid int foreign key references roles(roleid),
    primary key (userid, roleid)
)
查看更多
登录 后发表回答