当用户在索引视图中单击Checkbox时,我将更新数据库 这是我的视图代码(在视图中将DispalyFor更改为CheckBoxFor)
@Html.CheckBoxFor(modelItem => item.Active, new
{
data_url = Url.Action("Subscribe", "Home"),
data_id = item.Id,
})
并在ajax中写下这个
<script>
$(function() {
//var id, Active;
$('#item_Active').change(function () {
var ch = $(this).is(":checked");
var data = { 'id': $(this).data('id'), 'Active': ch };
//data[$(this).attr('name')] = $(this).is(':checked');
$.ajax({
url: $(this).data('url'),
type: 'POST',
data: data,
success: function() {
alert("Ok");
},
error: function(e) {
alert(e.toString());
}
});
});
});
</script>
我的控制器处于Home Action
[HttpPost]
public ActionResult Subscribe([Bind(Include = "id,Active")]Subscribe subscribe)
{
if (ModelState.IsValid)
{
var sub = db.Subscribes.FirstOrDefault(x => x.Id == subscribe.Id);
db.Entry(subscribe).State = EntityState.Modified;
db.SaveChanges();
}
return RedirectToAction("Index");
}
点击我的复选框时出现此错误
System.InvalidOperationException: Attaching an entity of type '' failed because another entity of the same type already has the same primary key value. This can happen when using the 'Attach' method or setting the state of an entity to 'Unchanged' or 'Modified' if any entities in the graph have conflicting key values. This may be because some entities are new and have not yet received database-generated key values. In this case use the 'Add' method or the 'Added' entity state to track the graph and then set the state of non-new entities to 'Unchanged' or 'Modified' as appropriate.
答案 0 :(得分:2)
从DB加载实体时,EF会跟踪该实体的任何更改。问题是您要让EF跟踪该类型的另一个实例(在您的情况下为subscribe
),与旧版本的Id
完全相同(在您的情况下为sub
)。
当EF通过Id
识别对象时,它不能有两个具有相同Id
类型的实例。所以一种可能的方法是修改旧的:
var sub = db.Subscribes.FirstOrDefault(x => x.Id == subscribe.Id);
sub.Active = subscribe.Active;
db.SaveChanges();