Reputation: 45
I need to update my database but I have an invalid argument in the SaveChanges()
statement.
What am I doing wrong?
foreach (ViewModels.QuestionVM0 f in qe.QuestionOptions0)
{
// loop through records to update
int aID = qe.ActivityID.Value;
int tID = qe.TaskID.Value;
int qNo = f.QuestionNo.Value;
Models.question1 questionCreate = new question1();
questionCreate.ActivityID = aID;
questionCreate.TaskID = tID;
questionCreate.QuestionNo = qNo;
db.SaveChanges(questionCreate);
}
Upvotes: 0
Views: 125
Reputation: 1380
Hope this will work well:
int aID, tID, qNo;
Models.question1 questionCreate;
foreach (ViewModels.QuestionVM0 f in qe.QuestionOptions0)
{
// loop through records to update
aID = qe.ActivityID.Value;
tID = qe.TaskID.Value;
qNo = f.QuestionNo.Value;
questionCreate = new question1();
questionCreate.ActivityID = aID;
questionCreate.TaskID = tID;
questionCreate.QuestionNo = qNo;
// For Insert new row
db.question1.Add(questionCreate);
// For Update exsisting row
db.Entry(questionCreate).State = EntityState.Modified;
db.SaveChanges();
}
You may call db.SaveChanges() after the loop.
Upvotes: 2
Reputation: 125650
You don't have to pass anything to SaveChanges
method. EF (I guess you use it) keeps tracking all your changes so it already knows what has to be updated.
db.SaveChanges();
Btw, you shouldn't call SaveChanges
on every iteration. Call it after foreach
instead to get SQL reached only once, not for every row again and again.
Upvotes: 0