c# - How can I save EntityFramework Model inside itself? -
i have model, called user (derived database) , i'm adding methods inside partial class, allowing user object maintenance type work.
as example, application update user's supervisorid in database in alignment database:
public partial class user { databaseentities db = new databaseentities(); otherentities otherdb = new commonentities(); public void updatesupervisor() { // lookup supervisor's username in other database: string supervisorusername = (from x in otherdb.vwemployees join y in otherdb.vwemployees on x.supervisor_eid equals y.employee_id x.user_id == searchusername select y.user_id).firstordefault(); // update database record supervisor of staff member: this.supervisoruserid = (from x in db.users x.adusername == supervisorusername select x.userid).firstordefault(); // @ point, this.supervisoruserid stores correct int, following command doesn't save changes. db.savechanges(); } }
the code works, except db.savechanges() doesn't save (no errors).
the method called outside of class, part of login processing:
public class login { // connect database: databaseentities db = new databaseentities(); user currentuser = new user(); // stuff... // update user's supervisor: currentuser.updatesupervisor(); }
any ideas?
thanks,
russell
your db object inside class different 1 in program calling method. also, user object might not exist in database. so, isn't simple setting property , saving.
you have pull item using db object inside class , update or add accordingly.
public partial class user { databaseentities db = new databaseentities(); otherentities otherdb = new commonentities(); public void updatesupervisor() { // lookup supervisor's username in other database: string supervisorusername = (from x in otherdb.vwemployees join y in otherdb.vwemployees on x.supervisor_eid equals y.employee_id x.user_id == searchusername select y.user_id).firstordefault(); // update database record supervisor of staff member this.supervisoruserid = (from x in db.users x.adusername == supervisorusername select x.userid).firstordefault(); // find user in dbcontext using primary key... var user = db.users.find(this.id); if (user != null) { // user exists in database, update id user.supervisoruserid = this.supervisoruserid; } else { // user not exist in database db.users.add(this); } db.savechanges(); } }
Comments
Post a Comment