ParPar
ParPar

Reputation: 7569

Why can't I add an object to the database? (mvc3)

It's quite a simple question: When someone click on "Edit Plan" in my ASP.NET MVC project - He doesn't edit but create a new plan with. You can see it more clearly in my answer to my qeustion here: How do I duplicate an object?

Now I want to do the same thing to its references, and I did it like that:

var featurePlans = db.FeaturePlanBaseSet.Where(f => f.PlanId == plan.Id).ToList();

db.PlanSet.AddObject(plan);
db.SaveChanges();

for (var i = 0; i < featurePlans.Count(); i++ )
{
   featurePlans[i].Plan = plan;
   db.FeaturePlanBaseSet.AddObject(featurePlans[i]);
}

Plan is added when I do AddObject, but Feature isn't.

I get this error:

An object with the same key already exists in the ObjectStateManager. The existing object is in the Unchanged state.

I'll be glad to know why does it happens.

Upvotes: 1

Views: 170

Answers (1)

Leons
Leons

Reputation: 2674

It does not appear that you save after adding FeaturePlanBaseSet. You need to call db.SaveChanges() last to save all changes.

EDIT: It also appears that you are reading an existing FeaturePlanBaseSet record from the database and then adding that record back. The next line will retrieve an existing record.

var featurePlans = db.FeaturePlanBaseSet.Where(f => f.PlanId == plan.Id).ToList(); 

When you add featurePlans[i], you are adding the existing record. If you plan to add a new record, Do it as follows:

for (var i = 0; i < featurePlans.Count(); i++ ) 
{ 
   var featurePlan = new FeaturePlanBaseSet();
   featurePlan.Plan = plan; 
   ...set other properties
   db.FeaturePlanBaseSet.AddObject(featurePlan); 
} 

Upvotes: 3

Related Questions