简体   繁体   English

使用EF模型在MVC中创建/更新不起作用

[英]Create/update in mvc using EF model not working

I am using an existing sql database in my MVC application. 我在MVC应用程序中使用现有的sql数据库。 For one of the tables, the create/update functions do not work. 对于其中一张表,创建/更新功能不起作用。 I am assuming it is because my application fails to retrieve the auto generated ID's defined in SQL and hence inserts a null value into a non nullable field resulting in the application breaking. 我以为是因为我的应用程序无法检索SQL中定义的自动生成的ID,因此将null值插入不可为null的字段中,从而导致应用程序损坏。 So, my question is how do i retrieved the auto generated fields defined in my sql database to show in my MVC5 application. 因此,我的问题是如何检索在sql数据库中定义的自动生成的字段以显示在MVC5应用程序中。 Many thanks to anybody who can assist. 非常感谢任何可以提供帮助的人。

Below is my database table for Customers: 以下是我的客户数据库表: 在此处输入图片说明

The Model: 该模型:

  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; }
}

Controller: 控制器:

[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);
    }

The View 风景

 <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> 

So, my question is how do i retrieved the auto generated fields defined in my sql database to show in my MVC5 application. 因此,我的问题是如何检索在sql数据库中定义的自动生成的字段以显示在MVC5应用程序中。

Follow steps 遵循步骤

  • Right click on the designer surface of the EDMX designer and click Update Model From Database ... 右键单击EDMX设计器的设计器表面,然后单击Update Model From Database ...”。

All entities are refreshed by default, new entities are only added if you select them. 默认情况下会刷新所有实体,只有在选择新实体后才添加它们。

EDIT: If it is not refreshing well. 编辑:如果它不是很好刷新。 Select all the tables and view-s in the EDMX designer. 在EDMX设计器中选择所有表和视图。 Delete them. 删除它们。 Then, update model from database 然后,从数据库更新模型

  • Right click On Model1.tt and select ' Run Custom Tool ' save and Build Now see classes are generated. Model1.tt单击鼠标右键,然后选择“ Run Custom Tool ”,然后保存并立即构建,请参见生成类。 Right click On Model1.Context.tt and select ' Run Custom Tool ' save and Build Now see property IN Context class is generated like Model1.Context.tt单击鼠标右键,然后选择“ Run Custom Tool ”,然后保存并立即构建,请参见属性IN上下文类的生成,例如

PS PS

Read this link also, it is very useful: http://blog.jongallant.com/2012/08/entity-framework-manual-update/ 还请阅读此链接,它非常有用: http : //blog.jongallant.com/2012/08/entity-framework-manual-update/

You should pass CustomerID to Controller as parameter. 您应该将CustomerID作为参数传递给Controller。 Don't give permission to CustomerID for null values and make it AUTO_INCREMENT 请勿授予客户ID空值的权限,并使其设为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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM