c# - 无法将对象添加到 context.DbSet。保存更改不起作用

标签 c# asp.net entity-framework

我在 Controller 中有这个 GET 方法:

public ActionResult Reserve(int id)
{
    ViewBag.staffID = new SelectList(context.Staffs, "staffID", "fName");
    ViewBag.roomID = id;
    return View();
}

对应 View :

@model _00002165.Models.Reservation

@{
    ViewBag.Title = "Reserve";
}

<h2>Reserve</h2>
 @using (Html.BeginForm()) {
    @Html.ValidationSummary(true)


    <div class="editor-label">
        <label>Room Number</label>
    </div>
    <div class="editor-field">
        <input type="text" value="@ViewBag.roomID" readonly name="roomID"/>
    </div>

    <div class="editor-label">
        @Html.LabelFor(model => model.fromDate)
    </div>
    <div class="editor-field">
        @Html.TextBoxFor(model => model.fromDate)
        @Html.ValidationMessageFor(model => model.fromDate)
    </div>
    <div class="editor-label">
        @Html.LabelFor(model => model.toDate)
    </div>
    <div class="editor-field">
        @Html.TextBoxFor(model => model.toDate)
        @Html.ValidationMessageFor(model => model.toDate)
    </div>

    <div class="editor-label">
        <label>Staff:</label>
    </div>
    <div class="editor-field">
        @Html.DropDownList("staffID", "Select Staff")
        @Html.ValidationMessageFor(model => model.staffID)
    </div>

   <button type="submit">Reserve</button>
}

我想使用这些 POST 方法保存来自这些输入的数据:

[HttpPost]
public ActionResult Reserve(Reservation res)
{
    if (ModelState.IsValid)
    {
        var customer = context.Customers.First(x => x.username == User.Identity.Name);
        res.customerID = customer.customerID;
        context.Reservation.Add(res);
        context.Entry(res).State = EntityState.Modified;
        context.SaveChanges();
        return RedirectToAction("Index");
    }
}

这给我以下错误:

Store update, insert, or delete statement affected an unexpected number of rows (0).

人们建议我将 @Html.HiddenFor(model => model.reservationID) 添加到我的 View 中。

但是 model.reservationID 是空的。

我该如何解决这个问题? 请帮忙

最佳答案

您不应该将数据传输对象传递到您的 View 或从您的 View 传出。使用将返回所需 DTO 的 ToModel 方法创建 View 模型。添加到上下文中,您不需要更改状态。

使用这个

context.Reservation.Add(res);
context.SaveChanges();

删除

context.Entry(res).State = EntityState.Modified;

如果您正在尝试更新,请从数据库中提取记录,进行更改并调用 SaveChanges

关于c# - 无法将对象添加到 context.DbSet。保存更改不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29929778/

相关文章:

C# 到 VB.NET 数组初始化

c# - 如何使用 ServiceStack.Net 实现客户端身份验证

c# - 如何与我在 C# 中生成的文本框同时创建 RequiredFieldValidator?

c# - 为什么 EF 在第一次调用方法中需要很长时间

performance - EF 性能 : ComputeHashValue() in query compilation

c# - 如何创建 SQL Server Compact 3.5 .sdf 文件并连接到它?

c# - 连接尝试失败,因为连接方在一段时间后没有正确响应或连接的主机未能响应

javascript - 如何禁用提交按钮并在 ASP.NET 回发完成时启用按钮

c# - 使用不同类型访问的 Entity Framework 性能

c# - 将 C# DataTable 的序列化实例转换为 java