Filip Gorgievski
Filip Gorgievski

Reputation: 39

Getting Exception when want to Save Changes to database

I am getting an exception when i want to change Values in database which are entered by the client. This is my all Customers in my database https://ibb.co/q1cwwYq when i click on one Customer I redirect client to Edit view which looks like this https://ibb.co/NSfvnGg. Now when i click save button I am getting error 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.

Here is my CustomerForm

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

Save Action in 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");
        }

Customer Class

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



    }
}

Where I am getting error on this line _context.SaveChanges(); of code.

Upvotes: 1

Views: 85

Answers (1)

Serge
Serge

Reputation: 43959

You have the bug

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

Should be

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

This is why you have an invalid Customer.MemberShipTypeId value and can't update.

Also for update try this code:

 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();

Upvotes: 1

Related Questions