1

美好的一天,我正在编写带有 SQL Server 2012 和 EF 捆绑包的 asp.net mvc3 项目,我使用下拉列表在数据库中创建和更新条目。添加页面时一切正常,但是当我尝试编辑时,它无法保存更改。我试图取括号并在调试模式下内部异常告诉

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>

我没有看到我的错误。有任何想法吗?

4

1 回答 1

0

你的班级页面用 [Bind(Exclude = "PageId")]

这意味着当您将 EntityState 设置为 Modified 时,实体没有主键 (id)

context.Entry(page).State = EntityState.Modified;
context.SaveChanges();

因此数据库无法保存更改

于 2013-08-25T19:09:50.933 回答