I'm using Web API 2 and Entity Framework 6 and Identity 2
I have product model which relates to an ApplicationUser
model, where I create Product
, I get an error:
Additional information: An entity object cannot be referenced by multiple instances of IEntityChangeTracker.
My model:
public class Product {
public int id { get; set; }
public string url { get; set; }
public string name {get;set}
public ApplicationUser user { get; set; }
}
My create code:
public IHttpActionResult PostProduct(Product product) {
ApplicationUserManager userManager = new ApplicationUserManager(new UserStore<ApplicationUser>(new ApplicationDbContext()));
product.user = userManager.FindById(User.Identity.GetUserId());
if (!ModelState.IsValid) {
return BadRequest(ModelState);
}
db.Products.Add(product);
db.SaveChanges();
return CreatedAtRoute("DefaultApi", new { id = product.id }, product);
}
What dbcontext does "db" refer to?
I would guess that you probably have more than one dbcontext and you are trying to retrieve data from one and persist it on another.
Maybe you can change the code to create just one dbcontext per http request and reuse that context during your http post request.
Maybe change:
ApplicationUserManager userManager = new ApplicationUserManager(new UserStore<ApplicationUser>(new ApplicationDbContext()));
to:
ApplicationUserManager userManager = new ApplicationUserManager(new UserStore<ApplicationUser>(db));
This will let you save your product but you should avoid sending back an EF object, or at least switch off lazy loading.
To clarify a bit, don't send product
back in the return as it contains properties which are EF proxies for lazy loading. This will cause at best, a lot more data than you want going back when you serialise the product object and at worst - the error you describe in the comments.