I am working on a C# asp.net 2010 web form web page I just wrote. Right now I am getting the error
'Cannot add an entity that already exists'. I get that error on the following line of code: attPlanDataContext.SubmitChanges();
I am trying to write to a table that has one to many rows that relate to the main table. When I try to add the second row to the table, that is when the error occurs.
I am hoping you can suggest what I need to change to fix this error. The following is the code that is affected by this error:
protected void submitbutton(object sender, EventArgs e)
{
if (!Page.IsPostBack)
return;
CustomerDataContext attDataContext = new CustomerDataContext();
Customer att = null;
att = new Customer();
InsertCustomer(att);
attDataContext.Customer.InsertOnSubmit(att);
attDataContext.SubmitChanges();
CustomerDataContext attPlanDataContext = new CustomerDataContext();
Plan attplan = null;
attplan = new Plan();
InsertPlans(attplan, att, attPlanDataContext);
}
protected void InsertCustomer(Customer att)
{
// fills in data here
}
protected void InsertPlans(Plan attplan,Customer att, CustomerDataContext attPlanDataContext)
{
for (int i = 0; i < ChkBoxLstPlan.Items.Count; i++)
{
if (ChkBoxLstPlan.Items[i].Selected)
{
attplan.Att_id = att.Att_id;
attplan.Number = ChkBoxLstPlan.Items[i].Value.Substring(0, 5);
// Update the database
attPlanDataContext.Plans.InsertOnSubmit(attplan);
attPlanDataContext.SubmitChanges();
}
}
}
Loading
Jean PaulPosted Oct 29, 2011, 3:39 PM
About your query: There is no need of new context for each row update.
I believe you can use single SubmitChanges() for all the updates.
My knowledge in entity framework says the problem could be in:
edmx mapping of relational tables
or
code shown above
Both of them requires the table structure for analysis.
scampercatPosted Oct 29, 2011, 6:18 PM
1. When I get to work on Monday I will try the create.
2. Apparently I am using linq to sql and not linq in the entity framework. My file is a .dbml and not a .edmx.
scampercatPosted Oct 29, 2011, 2:47 PM
Do I need to create a new instance of attPlanDataContext.Plans for each row I am adding to the Plans table? Can I submit just one final SubmitChanges() for all the rows added to the plans table?
Jean PaulPosted Oct 29, 2011, 9:44 AM
I will give a try here.