i trying create new link between 2 items exist.
the link table has:
{ userid - fk user table; roleid - fk role table; } the records linking exist in roles, , users tables.
using (entities db = new entities()) { ora_aspnet_users userstable = db.ora_aspnet_users .where(u => u.userid == userid).first(); userstable.ora_aspnet_roles .add(db.ora_aspnet_roles.where(c => c.roleid == roleid).first()); db.ora_aspnet_users.add(userstable); db.savechanges(); } the problem having is trying insert new record users tables , should inserting record link table.
you're adding user again when use add method, changes state of entity added. don't need if don't have disabled tracking changes or lazy loading.by default, entity framework performs detect changes automatically. try again deleting line:
using (entities db = new entities()) { ora_aspnet_users userstable = db.ora_aspnet_users.first(u => u.userid == userid); userstable.ora_aspnet_roles .add(db.ora_aspnet_roles.first(c => c.roleid == roleid)); db.savechanges(); } another thing don't need call where method, can pass same condition first method. problem if user or role doesn't exist, ef throw exception, better call firstordefault method , check if returned entity not null .
Comments
Post a Comment