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

不羁岁月 提交于 2020-01-06 07:27:07

问题


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

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:


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)
)


来源:https://stackoverflow.com/questions/50447212/how-can-i-get-a-list-of-linked-1-n-elements

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!