问题
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