使用viewmodel更新数据

时间:2016-02-07 10:58:32

标签: c# asp.net-mvc entity-framework viewmodel

我尝试使用viewmodel更新dataEntry并且我收到此错误信息:

  

存储更新,插入或删除语句会影响意外   行数(0)。自那以后,实体可能已被修改或删除   实体已加载。

据我所知,它显示ID丢失,但onDebug我可以c外国id(model.rgrade.SubjectId)我无法指出如何找到模型rgradeId(在结果中。< / p>

这是我的代码:

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

1 个答案:

答案 0 :(得分:1)

您不需要设置模型的状态。此外 - 当您知道集合中至少有一个实体时,您不需要使用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).