使用视图模型更新数据

update data using viewmodel

我正在尝试使用 viewmodel 更新 dataEntry,但收到此错误消息:

Store update, insert, or delete statement affected an unexpected number of rows (0). Entities may have been modified or deleted since entities were loaded.

据我所知,它显示 ID 丢失,但 onDebug 我可以获取外国 ID (model.rgrade.SubjectId) 我不知道如何在结果中找到模型 rgradeId(。

这是我的代码:

//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;
}

您应该不需要设置模型的状态。另外 - 当您知道集合中至少有一个实体时,您不需要使用 SingleOrDefault

此外 - 您是要使用 = +1 吗?这会将值设置为 1,而不是增加它。如果有,一般写成= 1.

如果你确实想增加它,你应该使用 += 1.

我会这样写:

// 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).