Note that there are some explanatory texts on larger screens.

plurals
  1. POEF: Update entity stored in session
    primarykey
    data
    text
    <p>I'm using EF 5 with Web Forms (ASP.NET 4.5), with the "one DbContext instance per request" approach. </p> <p>But this situation is a bit complicated: I have a multi-step create/edit screen, and I store the current entity in Session, then I manipulate it and in the final step, I commit it to the Database.</p> <p>Creating a new instance was fine, but I can't for the life of me edit an existing entity... Because it's another request, my original DbContext instance was lost and when I attach it to a new one, I get the <strong>An entity object cannot be referenced by multiple instances of IEntityChangeTracker</strong> error.</p> <p>My code is far too complex to post here, but I'll try and summarize it accurately:</p> <p>My DbContext:</p> <pre class="lang-cs prettyprint-override"><code>public class AppContext : DbContext { // DbSet declarations... public static AppContext Current { get { var context = HttpContext.Current.Items["Contexts.AppContext"] as AppContext; if (context == null) { context = new AppContext(); HttpContext.Current.Items["Contexts.AppContext"] = context; } return context; } } } </code></pre> <p>An example of what the page code looks like:</p> <pre class="lang-cs prettyprint-override"><code>protected void Page_Load(object sender, EventArgs e) { int? id = null; // After this, I try to get it from the QueryString, parse it, etc.. Omitted for sake of brevity // If I have an ID, it means I'm editing... Session["Product"] = id.HasValue ? new Product() : AppContext.Current.Products.Find(id)); MethodToPopulateFields(); // Internally, it uses the Session variable } protected void Step1(){ // through n // Manipulates the Session["Product"] based on page input... } protected void Save(){ var product = Session["Product"] as Product; if(product.ID == 0) product = AppContext.Current.Products.Add(product); // throws an exception: // AppContext.Current.Entry(product).State = EntityState.Modified; // this too: // AppContext.Products.Attach(product); AppContext.Current.SaveChanges(); } </code></pre> <p>I know I can get the old entity from the database, update it manually and save, all in the last step, but I really don't want to do that...</p> <p>Thank you.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload