我尝试使用以下actionresult更新EF5条目:
[HttpPost]
public ActionResult Edit(int id, IEnumerable<HttpPostedFileBase> files)
{
if (ModelState.IsValid)
{
Reference reference = db.References.Single(x => x.Id == id);
db.Entry(reference).State = EntityState.Modified;
db.SaveChanges();
//Other stuff regarding files/images
return RedirectToAction("Index");
}
return View();
}
什么都没发生。当我调试它时,它会通过代码,因为一切都很好。但是db中没有更新任何内容。
如果需要,可以在这里找到模型:
public class Reference
{
public int Id { get; set; }
public string Headline { get; set; }
public string Text { get; set; }
public DateTime Date { get; set; }
public IEnumerable<HttpPostedFileBase> ImageUploadMain { get; set; }
public String MainFileName { get; set; }
public IEnumerable<HttpPostedFileBase> ImageUpload { get; set; }
public virtual ICollection<Image> Files { get; set; }
public virtual ICollection<RefProperties> Properties { get; set; }
public int CategoryId { get; set; }
public virtual Category Category { get; set; }
}
public class Image
{
public int Id { get; set; }
public string FileName { get; set; }
public virtual Reference Reference { get; set; }
}
public class RefProperties
{
public int Id { get; set; }
public string Key { get; set; }
public string Value { get; set; }
}
public class Category
{
public int CategoryId { get; set; }
public string Name { get; set; }
public virtual ICollection<Reference> References { get; set; }
}
相关参赛作品不仅没有更新,而且主要属性如&#34;标题&#34;无法更新。我究竟做错了什么?创建/删除工作正常btw。
答案 0 :(得分:1)
正如Gert Arnold所说,您实际上并未修改任何Reference
值,因此不会更新任何内容。通过致电db.Entry(reference).State = EntityState.Modified
,您只需将检索到的实体状态设置为ChangeTracker
中的修改状态即可。当您致电SaveChanges
()时,它将使用您提取的相同值更新数据库中的参考记录。
您需要更新一些Reference实例属性才能看到更改。
[HttpPost]
public ActionResult Edit(int id, IEnumerable<HttpPostedFileBase> files)
{
if (ModelState.IsValid)
{
Reference reference = db.References.Single(x => x.Id == id);
reference.HeaderText = "Changed";
/* No need to interact with the change tracker as the entity is already tracked and you've made a change */
// db.Entry(reference).State = EntityState.Modified;
/* Create/Modify/Update/Delete other entities */
db.SaveChanges();
//Other stuff regarding files/images
return RedirectToAction("Index");
}
return View();
}
答案 1 :(得分:0)
这是我在寻找的东西:
TryUpdateModel(reference, "");
它有一大堆重载。这虽然有效