code first - Updating entity framework entity with many to many relationship -


i have (2) entities, follows:

[table("user")] public class user {     [key]     [databasegeneratedattribute(databasegeneratedoption.identity)]     public int userid { get; set; }     [required]     [maxlength(20)]     public string name { get; set; }     public icollection<role> roles { get; set; }      public user()     {         this.roles = new collection<role>();     } }   [table("user")] public class role {     [key]     [databasegeneratedattribute(databasegeneratedoption.identity)]     public int roleid{ get; set; }     [required]     [maxlength(20)]     public string name { get; set; }     public icollection<user> users { get; set; }      public role()     {         this.users = new collection<user>();     } } 

this creates 3 tables in database, user, role , userrole.

i leveraging generic repository, add , update following:

    public virtual void add(tentity entity)     {         _dbset.add(entity);     }      public virtual void update(tentity entity)     {         _dbset.attach(entity);         _dbcontext.entry(entity).state = entitystate.modified;     } 

if want add new user roles, have following in userrepository, inherits generic repository.

    public override void add(user entity)     {         foreach (var role in entity.roles)             _dbcontext.roles.attach(role);          base.add(entity);     } 

this seems clunky, works.

my trouble when want update user, add new role. thought similar.

    public override void update(user entity)     {         foreach (var role in entity.roles)             _dbcontext.roles.attach(role);          base.update(entity);     } 

but not work ... ideas on doing wrong appreciated!

update

my use case have existing user x roles, add y number of roles, want update user y number of new roles.

you shouldn't need that. if role not yet exist, this:

var user = new user { name="fred" } user.roles.add(new role { name="accounting" });  context.add(user); 

if adding existing role, need role first

var role = context.roles.single(x => x.name="accounting");  var user = new user { name="fred" } user.roles.add(role);  context.add(user); 

Comments

Popular posts from this blog

linux - xterm copying to CLIPBOARD using copy-selection causes automatic updating of CLIPBOARD upon mouse selection -

c++ - qgraphicsview horizontal scrolling always has a vertical delta -