Wiliam Cardoso
Wiliam Cardoso

Reputation: 444

Entity Framework: “Store update, insert, or delete statement affected an unexpected number of rows (0).”

Using MVC5 code first, trying to edit any of my models gives me this error: Entity Framework: “Store update, insert, or delete statement affected an unexpected number of rows (0).” Here is my Controller and the debugger is calling the error at db.SaveChanges();, but I have no idea why.

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

    // POST: Artists/Edit/5
    // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
    // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Edit([Bind(Include = "ID,Name,Picture,BirthDate,Nationality,ArtStyle,Info,Rating,Artwork1,Artwork2,Artwork3")] Artist artist)
    {
        if (ModelState.IsValid)
        {
            db.Entry(artist).State = EntityState.Modified;
            db.SaveChanges();
            return RedirectToAction("Index");
        }
        return View(artist);
    }

artist model:

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Data.Entity;

namespace ArtistDatabase.Models
{
    public class Artist
    {
        [Key]
        public int ArtistID { get; set; }
        //----------------------------------------------------------------------------------------------
        [Required,StringLength(60, MinimumLength = 3), Display(Name = "Artist")]
        public string Name { get; set; }
        //----------------------------------------------------------------------------------------------
        [DataType(DataType.ImageUrl)]
        public string Picture { get; set; }
        //----------------------------------------------------------------------------------------------
        [System.ComponentModel.DataAnnotations.Schema.Column(TypeName = "datetime2")]
        [Display(Name = "Date of Birth"),DataType(DataType.Date),DisplayFormat(DataFormatString = "{0:dd-MM-yyyy}", ApplyFormatInEditMode = true)]
        public DateTime BirthDate { get; set; }
        //----------------------------------------------------------------------------------------------
        [Required,StringLength(30)]
        public string Nationality { get; set; }
        //----------------------------------------------------------------------------------------------
        [Display(Name = "Style/Movement")]
        public string ArtStyle { get; set; }
        //----------------------------------------------------------------------------------------------
        [DataType(DataType.MultilineText)]
        public string Info { get; set; }
        //----------------------------------------------------------------------------------------------
        [RegularExpression(@"^[A-Z]+[a-zA-Z''-'\s]*$")]
        [StringLength(5)]
        public string Rating { get; set; }
        //----------------------------------------------------------------------------------------------
        [Display(Name = "Famous work: "),DataType(DataType.ImageUrl)]
        public string Artwork1 { get; set; }
        //----------------------------------------------------------------------------------------------
        [Display(Name = " "), DataType(DataType.ImageUrl)]
        public string Artwork2 { get; set; }
        //----------------------------------------------------------------------------------------------
        [Display(Name = " "), DataType(DataType.ImageUrl)]
        public string Artwork3 { get; set; }
        //----------------------------------------------------------------------------------------------
        public virtual ICollection<Artwork> Artworks { get; set; }
    }

    public class ArtistDBContext : DbContext
    {
        public DbSet<Artist> Artists { get; set; }
        public DbSet<Artwork> Artworks { get; set; }
    }
}

edit view:

@model ArtistDatabase.Models.Artist

@{
    ViewBag.Title = "Edit";
}

<h2>Edit</h2>


@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()

    <div class="form-horizontal">
        <h4>@Html.DisplayFor(model => model.Name)</h4>
        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        @Html.HiddenFor(model => model.ArtistID)

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

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

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

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

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

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

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

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

        <div class="form-group">
            @Html.LabelFor(model => model.Artwork3, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Artwork3, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Artwork3, "", new { @class = "text-danger" })
            </div>
        </div>
    </div>
    <hr />
    <div class="row">
        <div class="col-sm-6 text-left">
            @using (Html.BeginForm())
            {
                <div class="form-actions">
                    <input type="submit" value="Save" class="btn btn-default" />
                    @Html.ActionLink("Cancel", "Details", new { id = Model.ArtistID }, new { @class = "btn btn-default" })
                </div>             
            }    
        </div>
       <div class="col-sm-6 text-right">
        @Html.ActionLink("Profile", "Details", new { id = Model.ArtistID }, new { @class = "btn btn-default" })
        @Html.ActionLink("Artists", "Index", null, new { @class = "btn btn-default" })
        </div>
    </div>
}


@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}

you can go here to test: http://www.artistdb.willcardoso.net/

Upvotes: 0

Views: 2183

Answers (2)

S.Dav
S.Dav

Reputation: 2466

Your binding is not correct. You are using:

public ActionResult Edit([Bind(Include = "ID,Name,Picture,BirthDate,Nationality,ArtStyle,Info,Rating,Artwork1,Artwork2,Artwork3")] Artist artist)

But the Key is ArtistID

The ID should be ArtistID in the bindings.

Upvotes: 1

Spedo De La Rossa
Spedo De La Rossa

Reputation: 127

You can solve this by either A) modifying the save call to Add the object, or B) just don't change the primary key on edit. I did B).

Upvotes: 1

Related Questions