c# - Force reload of entity in Entity Framework after insert/add -
i have project
entity, defined as:
public class project { [key] public guid projectid { get; set; } //... [required, foreignkey("user")] public guid userid { get; set; } public virtual user user { get; set; } }
in controller, have:
// insert public ihttpactionresult post([frombody] projectdto projectdto) { return save(projectdto); } // update public ihttpactionresult post(guid id, [frombody] projectdto projectdto) { return save(projectdto); } private ihttpactionresult save(projectdto projectdto) { if (!modelstate.isvalid) return badrequest(modelstate); var isnew = projectdto.projectid == guid.empty; project project; if (isnew) { project = new project(); var user = usermanager.findbyname(user.identity.name); projectdto.userid = new guid(user.userid.tostring()); dbcontext.entry(project).state = entitystate.added; } else { project= dbcontext.projects.find(projectdto.projectid); if (project == null) return notfound(); dbcontext.entry(project).state = entitystate.modified; } // set fields dto user... dbcontext.savechanges(); // issue: return ok(project); }
the issue when newly inserted project returned controller, virtual field user
null because hasn't been loaded/populated user data.
on line // issue:
tried both of these lines:
if (isnew) { // try 1 of these 2 lines: dbcontext.entry(project).reload(); project = dbcontext.projects.find(project.projectid); }
but both had no effect: assume using find
not going database because entity exists in context, returns that. have thought reload have forced full reload of project fk relationships, didn't.
i this:
if (isnew) { project.user = dbcontext.users.find(project.userid); }
but doesn't clean i'd like: i'd have each fk i'm returning.
what's best way handle this?
you can detach first, should force reloading upong finding:
dbcontext.entry(project).state = entitystate.detached; project = dbcontext.projects.find(project.projectid);
if doesn't work, detach using objectcontext
instead, stop working on future versions of ef (where dbcontext
doesn't use objectcontext
):
((iobjectcontextadapter)dbcontext).objectcontext.detach(project);
Comments
Post a Comment