【问题标题】:Create/update in mvc using EF model not working使用 EF 模型在 mvc 中创建/更新不起作用
【发布时间】:2017-12-25 17:40:52
【问题描述】:

我在我的 MVC 应用程序中使用现有的 sql 数据库。对于其中一张表,创建/更新功能不起作用。我假设这是因为我的应用程序无法检索在 SQL 中定义的自动生成的 ID,因此将空值插入到不可为空的字段中,从而导致应用程序中断。所以,我的问题是如何检索在我的 sql 数据库中定义的自动生成字段以显示在我的 MVC5 应用程序中。非常感谢任何可以提供帮助的人。

下面是我的客户数据库表:

模型:

  public partial class Customer
{
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
    public Customer()
    {
        this.Cards = new HashSet<Card>();
        this.Stores = new HashSet<Store>();
    }

    public int CustomerID { get; set; }
    public int DiscountLevelID { get; set; }
    public int LoyaltyLevelID { get; set; }
    public string CustomerCompanyName { get; set; }
    public string CustomerName { get; set; }
    public string CustomerSurname { get; set; }

    [DatabaseGenerated(DatabaseGeneratedOption.Computed)]
    public string CustomerGUID { get; set; }
    public int CustomerStatus { get; set; }
    public string CustomerAddress { get; set; }
    public string CustomerTel { get; set; }
    public string CustomerCel { get; set; }
    public Nullable<int> CustomerNumber { get; set; }
    public string CustomerContact { get; set; }
    public string CustomerLogo { get; set; }
    public string CustomerLogoPath { get; set; }
    public int LastStoreCustomerSyncID { get; set; }

    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
    public virtual ICollection<Card> Cards { get; set; }
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
    public virtual ICollection<Store> Stores { get; set; }
}

控制器:

[HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create([Bind(Include = "CustomerID,DiscountLevelID,LoyaltyLevelID,CustomerCompanyName,CustomerName,CustomerSurname,CustomerGUID,CustomerStatus,CustomerAddress,CustomerTel,CustomerCel,CustomerNumber,CustomerContact,CustomerLogo,CustomerLogoPath,LastStoreCustomerSyncID")] Customer customer)
    {
        if (ModelState.IsValid)
        {
            db.Customers.Add(customer);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        return View(customer);
    }

    // GET: Companies/Edit/5
    public ActionResult Edit(int? id)
    {
        if (id == null)
        {
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }
        Customer customer = db.Customers.Find(id);
        if (customer == null)
        {
            return HttpNotFound();
        }
        return View(customer);
    }

    // POST: Companies/Edit/5

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Edit([Bind(Include = "CustomerID,DiscountLevelID,LoyaltyLevelID,CustomerCompanyName,CustomerName,CustomerSurname,CustomerGUID,CustomerStatus,CustomerAddress,CustomerTel,CustomerCel,CustomerNumber,CustomerContact,CustomerLogo,CustomerLogoPath,LastStoreCustomerSyncID")] Customer customer)
    {
        if (ModelState.IsValid)
        {
            db.Entry(customer).State = EntityState.Modified;
            db.SaveChanges();
            return RedirectToAction("Index");
        }
        return View(customer);
    }

观点

<div class="form-group">
            @Html.LabelFor(model => model.CustomerGUID, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.CustomerGUID, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.CustomerGUID, "", new { @class = "text-danger" })
            </div>
        </div>

【问题讨论】:

  • 对数据库做SaveChanges时是否出现错误?使用了哪个 EF 模型(代码优先/数据库优先/模型优先)?包括在创建/更新操作期间发现的错误。还要确保你已经在视图中设置了一个隐藏字段CustomerID。
  • 是的,它发生在 SaveChanges。我先用 db。
  • 那里说了什么错误?问题实际上可能发生在数据库中或您如何插入数据(您是否从数据库更新了模型?)。还要检查错误中的内部异常,以确保我们确定您遇到了什么样的问题。
  • 它现在没有给出任何错误但它仍然没有插入数据库:(。我确实从数据库更新了模型
  • 这是错误:{“一个或多个实体的验证失败。有关更多详细信息,请参阅 'EntityValidationErrors' 属性。”}... {System.Data.Entity.Validation.DbEntityValidationResult}跨度>

标签: c# sql entity-framework asp.net-mvc-5


【解决方案1】:

所以,我的问题是如何检索自动生成的字段 在我的 sql 数据库中定义以显示在我的 MVC5 应用程序中。

按照步骤进行

  • 右键单击 EDMX 设计器的设计器表面,然后单击 Update Model From Database...

默认情况下会刷新所有实体,仅当您选择它们​​时才会添加新实体。

编辑:如果它不能很好地刷新。 选择 EDMX 设计器中的所有表和视图。 删除它们。 然后,从数据库更新模型

  • 右键单击Model1.tt 并选择“Run Custom Tool”保存并立即构建,看看生成的类。 右键单击 On Model1.Context.tt 并选择“Run Custom Tool”保存并构建现在看到属性 IN Context 类的生成类似于

附言

也请阅读此链接,它非常有用:http://blog.jongallant.com/2012/08/entity-framework-manual-update/

【讨论】:

    【解决方案2】:

    您应该将 CustomerID 作为参数传递给 Controller。不要向 CustomerID 授予空值权限并将其设为 AUTO_INCREMENT

    <div class="form-group">
        @Html.TextBoxFor(model => model.CustomerID, new {style = 'display:none'})
        @Html.LabelFor(model => model.CustomerGUID, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.CustomerGUID, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.CustomerGUID, "", new { @class = "text-danger" })
        </div>
    </div>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-13
      • 2017-05-15
      • 1970-01-01
      相关资源
      最近更新 更多