I am trying to add the same object(just changing a property) multiple time to the database, but the problem is after adding the first record to the database the record get an id and the other records cannot be added.
My model:
class MyClass{
int id {set;get;}
string name {set;get;}
string color {set;get;}
//and other properities.
}
My Controller :
public ActionResult Test(MyClass obj,int Counter){
for(int i=0;i<Counter;i++){
MyClass NewObject=obj;
NewObject.name=obj.name+" "+i.ToString();
Db.MyClass.Add(NewObject);
Db.SaveChanges();
}
}
For example if my object is : name="theName";Color="Red"; And the counter is 3; So my expected output is :
- First record: name="theName 0";Color="Red";
- Second record: name="theName 1";Color="Red";
- Third record: name="theName 2";Color="Red";
But what happens is after the first record be added NewObject will have an id but the problem that is obj have also id although I didn't add it to the database! So the second record will return an error ('The changes to the database were committed successfully, but an error occurred while updating the object context.')
counter- 1 times.