I am trying to execute the following code in a ASP .Net web page:
using (var wpe = new CL40215_wpnEntities())
{
int cid = Convert.ToInt32(cmbCity.SelectedItem.Value);
int catid = Convert.ToInt32(cmbCategory.SelectedValue);
Post p = new Post
{
title = txtTitle.Text,
description = txtDescription.Text,
User = u,
City = wpe.Cities.First(c => c.id == cid),
initialprice = 0,
finalprice = 10,
Category = wpe.Categories.First(c => c.id == catid),
postdate = DateTime.Now,
closedate = DateTime.Now.AddDays(Convert.ToInt32(cmbDays.SelectedValue)),
currentprice = 1
};
wpe.AddToPosts(p);
wpe.SaveChanges();
}
However, I get the following error:
The relationship between the two objects cannot be defined because they are attached to different ObjectContext objects.
Does anyone have any idea why is this happening, and how to solve this issue?
Try changing your object initialisation to attach the post object first then create the relationship.
If you are using persistence aware classes, they need to know about each other before the relationship can be created. That means you will either need to detach the children before building the object, then attach them all children first, or, as above, attach the new post first. Not sure what youre addtoposts repo call is doing, but that should work provided you aren’t running a save changes before the object is valid.
EDIT: Apologies. I didn’t notice the user object being added. You will need to either reload the user with the current context or DETACH the user from it’s previous context and ATTACH it to the current one.