我有这个问题类。有吗
public class Issue
{
public int IssueId { get; set; }
[Required]
public string ReporterName { get; set; }
[Required]
public string Description { get; set; }
public int? IssueTypeId { get; set; }
public virtual IssueType type { get; set; }
}
然后这是我的视图,所以我可以更改IssueTypeId的值。但是,当我尝试使用控制器中的代码将其保存在数据库中时,我收到一条错误消息,指出仍然需要ReporterName和Description。我怎样才能更新数据库中的一个特定值,在本例中为IssueTypeId?
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Issue</h4>
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
@Html.HiddenFor(model => model.IssueId)
<div class="form-group">
@Html.LabelFor(model => model.IssueTypeId, "IssueTypeId", htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownList("IssueTypeId", null, htmlAttributes: new { @class = "form-control" })
@Html.ValidationMessageFor(model => model.IssueTypeId, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Save" class="btn btn-default" />
</div>
</div>
</div>
}
我在控制器中的代码
public ActionResult AssignFixer(int issueId, int issueTypeId)
{
var issue = new Issue { IssueId = issueId , IssueTypeId= issueTypeId};
using (var newContext = new SystemContext())
{
newContext.Issues.Attach(issue);
newContext.Entry(issue).Property(i => i.IssueTypeId).IsModified = true;
newContext.SaveChanges();
}
return View(issue);
}
答案 0 :(得分:3)
而不是在issue
附加newContext.Issues
。首先获取实例然后更新它。喜欢:
var existingIssue = newContext.Issues.Where(i => i.IssueId == issueId).FirstOrDefault();
existingIssue.IssueTypeId = issueTypeId;
newContext.SaveChanges();