首页 > 解决方案 > 想要将更改保存到数据库时出现异常

问题描述

当我想更改客户端输入的数据库中的值时,出现异常。这是我数据库中的所有客户,https://ibb.co/q1cwwYq当我单击一个客户时,我将客户重定向到看起来像这样的编辑视图https://ibb.co/NSfvnGg。现在,当我单击保存按钮时,出现错误System.Data.Entity.Infrastructure.DbUpdateException: 'An error occurred while updating the entries. See the inner exception for details.'

SqlException: The UPDATE statement conflicted with the FOREIGN KEY constraint "FK_dbo.Customers_dbo.MemberShipTypes_MemberShipTypeID". The conflict occurred in database "Vidly.Models.ApplicationDbContext", table "dbo.MemberShipTypes", column 'Id'.
The statement has been terminated.

这是我的客户表格

@model Vidly.Models.NewCustomerViewModel
@{
    ViewBag.Title = "New";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<h2>New Customer</h2>

@using (Html.BeginForm("Save", "Customer"))
{
    <div class="form-group">
        @Html.LabelFor(m => m.Customer.Name)
        @Html.TextBoxFor(m => m.Customer.Name, new { @class = "form-control" })
    </div>

    <div class="form-group">
        @Html.LabelFor(m => m.Customer.Birthdate)
        @Html.TextBoxFor(m => m.Customer.Birthdate,"{0:d MMM yyyy}", new { @class = "form-control" })
    </div>

   

    <div class="form-group">
        @Html.LabelFor(m => m.Customer.MemberShipTypeID)
        @Html.DropDownListFor(m => m.Customer.MemberShipType,new SelectList(Model.MemberShipTypes,"ID","Name"),"", new { @class = "form-control" })
    </div>

    <div class="checkbox">
        <label>
            @Html.CheckBoxFor(m => m.Customer.IsSubscribedToNewsLetter) Subscribed to Newsletter?
        </label>
    </div>

    @Html.HiddenFor(m => m.Customer.Id);

    <button type="submit" class="btn btn-primary">Save</button>
}

在 CustomerController 中保存操作

public ActionResult Save(Customer customer)
        {   
            if(customer.Id == 0)
                _context.Customers.Add(customer);
            else
            {
                var customerInDb = _context.Customers.Single(c => c.Id == customer.Id);

                customerInDb.Name = customer.Name;
                customerInDb.Birthdate = customer.Birthdate;
                customerInDb.IsSubscribedToNewsLetter = customer.IsSubscribedToNewsLetter;
                customerInDb.MemberShipTypeID = customer.MemberShipTypeID;


            }
            _context.SaveChanges();


            return RedirectToAction("Customers", "Customer");
        }

客户类

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;

namespace Vidly.Models
{
    public class Customer
    {
        
        public int Id { get; set; }
        [Required] [StringLength(255)]
        public  string  Name { get; set; }

        public bool IsSubscribedToNewsLetter { get; set; }

        public MemberShipType MemberShipType { get; set; }

        [Display(Name = "Membership Type")]
        public byte MemberShipTypeID { get; set; }

        [Display(Name = "Date of Birth")]
        public DateTime? Birthdate { get; set; }



    }
}

我在这行_context.SaveChanges();代码中遇到错误的地方。

标签: c#asp.net-mvcdatabaseentity-framework

解决方案


你有错误

@Html.DropDownListFor(m => m.Customer.MemberShipType,new SelectList(Model.MemberShipTypes,"ID","Name"),"", new { @class = "form-control" })

应该

@Html.DropDownListFor(m => m.Customer.MemberShipTypeId,new SelectList(Model.MemberShipTypes,"ID","Name"),"", new { @class = "form-control" })

这就是您的 Customer.MemberShipTypeId 值无效且无法更新的原因。

也为了更新试试这个代码:

 var customerInDb = _context.Customers.FirstOrDefault(c => c.Id == customer.Id);

if (customerInDb !=null)
{

  customerInDb.Name = customer.Name;
    customerInDb.Birthdate = customer.Birthdate;
   customerInDb.IsSubscribedToNewsLetter = customer.IsSubscribedToNewsLetter;
 customerInDb.MemberShipTypeID = customer.MemberShipTypeID;

_context.Entry(CustomerInDb).State = EntityState.Modified;

}
....

 _context.SaveChanges();


推荐阅读