c# - Entity Framework and roles -
i have problem. have user can have many roles, roles global, have set table construction follows:
create table [dbo].[users]( [id] [nvarchar](128) not null, [username] [nvarchar](max) null, [email] [nvarchar](max) null, [datecreated] [datetime] not null, [datemodified] [datetime] null, [lastlogindate] [datetime] not null, [passwordhash] [nvarchar](max) null, constraint [pk_dbo.users] primary key clustered create table [dbo].[userroles]( [userid] [nvarchar](128) not null, [roleid] [nvarchar](128) not null, constraint [pk_dbo.userroles] primary key clustered ( [userid] asc, [roleid] asc ) create table [dbo].[roles]( [id] [nvarchar](128) not null, [name] [nvarchar](max) null, constraint [pk_dbo.roles] primary key clustered ( [id] asc )
the userroles table has foriegn keys set both roles , users table on respective id columns.
in code, have this:
public class user : iuser { public string id { get; set; } // stripped brevity public ilist<userrole> roles { get; set; } public user() { this.id = guid.newguid().tostring(); } } public class userrole { public string roleid { get; set; } public string userid { get; set; } } public class role : irole { public string id { get; set; } public string name { get; set; } public ilist<userrole> users { get; set; } public role() { this.id = guid.newguid().tostring(); } }
entityframework fine class , mapping follows:
modelbuilder.entity<userrole>().haskey(m => new { m.userid, m.roleid });
everything mapping works. like, user class have list of roles , not userroles.
so, this:
public class user : iuser { public string id { get; set; } // stripped brevity public ilist<role> roles { get; set; } public user() { this.id = guid.newguid().tostring(); } }
i sure can see problem here. can think of solution table construction stays same, can access roles instead of userroles?
sorry if explanation not good.
i think you're after this...
in dbcontext:
protected override void onmodelcreating(dbmodelbuilder modelbuilder) { modelbuilder.entity<user>() .hasmany(x => x.roles) .withmany(x => x.users) .map(x => { x.mapleftkey("userid"); x.maprightkey("roleid"); x.totable("userrole"); }); }
now have.
class user { icollection<role> roles {get; set;} }
and
class role { icollection<user> users {get; set;} }
c# entity-framework
No comments:
Post a Comment