Reputation: 301
I'm trying to update dataEntry using viewmodel and I'm getting this error msg :
Store update, insert, or delete statement affected an unexpected number of rows (0). Entities may have been modified or deleted since entities were loaded.
As far as I understand it's showing the ID is missing , but onDebug I can c the foreign id (model.rgrade.SubjectId
) I cant finger out how to find the model rgradeId( in the results.
This is my code :
//checked if the subject name is allready in the db
var subjectNameQuery = db.Subject.Where(n => n.SubjectName.ToLower().Equals(model.sub.SubjectName));
if (subjectNameQuery.Count() > 0)
{
//if the name is in the table, do Not add the name of the Id again
model.rev.SubjectId = subjectNameQuery.SingleOrDefault().SubjectId;
model.rgrade.SubjectId = subjectNameQuery.SingleOrDefault().SubjectId;
if (model.rev.GBU == "Good")
{
model.rgrade.Good = +1;
}
else if (model.rev.GBU == "Bad")
{
model.rgrade.bad = +1;
}
else if (model.rev.GBU == "Ugly")
{
model.rgrade.Ugly = +1;
}
db.Entry(model.rgrade).State = EntityState.Modified;
}
Upvotes: 0
Views: 250
Reputation: 5791
You shouldn't need to set the state of the model. Also - you don't need to use SingleOrDefault
when you know there will be at least one entity in the collection.
Also - did you mean to use = +1
? This would set the value to 1, rather than increment it. If so, it's usually written = 1
.
If you did mean to increment it you should use += 1
.
Here's how I would have written it:
// Check if the subject name is already in the db.
var subjects = db.Subject.Where(s => s.SubjectName.Equals(model.sub.SubjectName, StringComparison.CurrentCultureIgnoreCase));
// If the name is in the table, do not add the name of the Id again.
if (subjects.Any())
{
return;
}
var subjectId = subjects.First().Id;
model.rev.SubjectId = subjectId;
model.rgrade.SubjectId = subjectId;
if (model.rev.GBU == "Good")
{
model.rgrade.Good = += 1;
}
else if (model.rev.GBU == "Bad")
{
model.rgrade.bad = += 1;
}
else if (model.rev.GBU == "Ugly")
{
model.rgrade.Ugly += 1;
}
// Save the entity (no need to set the state).
Upvotes: 1