美好的一天, 我正在编写带有SQL Server 2012& s捆绑软件的asp.net mvc3项目。 EF,我使用dropdownlist for create&更新数据库中的条目。当我添加页面时,一切正常,但是当我尝试编辑它时,无法保存更改。我试图采取brackpoint并在调试模式下内部异常告诉
Store update, insert, or delete statement affected an unexpected number of rows (0). Entities may have been modified or deleted since entities were loaded. Refresh ObjectStateManager entries.
这是我的代码:
[Table("Pages", Schema = "myprojectname")]
[Bind(Exclude = "PageId")]
public class Page
{
public int PageId { get; set; }
public string PageContent { get; set; }
public int PageTitleId { get; set; }
public virtual PageTitle PageTitle { get; set; }
}
[Table("PageTitles", Schema = "myprojectname")]
public class PageTitle
{
public int PageTitleId { get; set; }
public string Title { get; set; }
public List<Page> Pages { get; set; }
}
public DbSet<Page> Pages { get; set; }
public DbSet<PageTitle> PageTitles { get; set; }
public ActionResult PageEdit(int id)
{
Page page = context.Pages.Find(id);
ViewBag.PageTitleId = new SelectList(context.PageTitles, "PageTitleId", "Title", page.PageTitleId);
return View(page);
}
[HttpPost]
[ValidateInput(false)]
public ActionResult PageEdit(Page page)
{
try
{
if (ModelState.IsValid)
{
context.Entry(page).State = EntityState.Modified;
context.SaveChanges();
return RedirectToAction("Index", "Administrator");
}
}
catch (DataException)
{
ModelState.AddModelError("", "Unable to save changes. Please try again");
}
ViewBag.PageTitleId = new SelectList(context.PageTitles, "PageTitleId", "Title", page.PageTitleId);
return View(page);
}
@model BalticCenter.Web.Models.Entities.SitePages.Page
@{
ViewBag.Title = "PageEdit";
Layout = "~/Views/Shared/_AdministratorLayout.cshtml";
}
<h2>PageEdit</h2>
@using (Html.BeginForm()) {
@Html.ValidationSummary(true)
<fieldset>
<legend>Page</legend>
@Html.HiddenFor(x => x.PageId)
<div class="editor-label">
@Html.LabelFor(model => model.PageTitleId, "PageTitle")
</div>
<div class="editor-field">
@Html.DropDownList("PageTitleId", String.Empty)
@Html.ValidationMessageFor(model => model.PageTitleId)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.PageContent)
</div>
<div class="editor-field">
@Html.TextAreaFor(model => model.PageContent)
@Html.ValidationMessageFor(model => model.PageContent)
</div>
<p>
<input type="submit" value="Edit" />
</p>
</fieldset>
}
<div>
@Html.ActionLink("Back to List", "Index")
</div>
我没有看到我的错误。有什么想法吗?
答案 0 :(得分:0)
您的班级页面装饰有[Bind(Exclude =“PageId”)]
这意味着当您将EntityState设置为Modified时,Entity没有质量密钥(id)
context.Entry(page).State = EntityState.Modified;
context.SaveChanges();
因此数据库无法保存更改