ddeamaral
ddeamaral

Reputation: 1443

Entity Framework Code First Identity Insert Exception

So I am having an issue inserting a record with an integer ID field using Entity Framework and using the code first approach. When I try to insert a record with an ID of 0 or an ID of null, I get the following exception

Additional information: Store update, insert, or delete statement affected an >unexpected number of rows (0). Entities may have been modified or deleted since >entities were loaded. See http://go.microsoft.com/fwlink/?LinkId=472540 for >information on understanding and handling optimistic concurrency exceptions.

this is the code that is in my controller

    // POST: Products/Create
    // 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 Create([Bind(Include = "Product_ID,PageURL,Name,Code,Description,Category_ID,Price,DateCreated,DateModified,Featured")] Product product)
    {

        product.DateCreated = DateTime.Now;
        product.DateModified = DateTime.Now;

        if (ModelState.IsValid)
        {
            db.Products.Add(product);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        ViewBag.Category_ID = new SelectList(db.Categories, "Category_ID", "CategoryName", product.Category_ID);
        return View(product);
    }

and this is the model for that entity being inserted

namespace SeniorProjectMVC.Models
{
    using System;
    using System.Collections.Generic;
    using System.ComponentModel.DataAnnotations;
    using System.ComponentModel.DataAnnotations.Schema;
    using System.Data.Entity.Spatial;

    [Table("Product")]
    public partial class Product
    {
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
        public Product()
        {
            OrderLines = new HashSet<OrderLine>();
            SKU_Table = new HashSet<SKU_Table>();
            XREF_CatalogProduct = new HashSet<XREF_CatalogProduct>();
        }

        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public int ID { get; set; }

        public string FormattedPrice { get { return this.Price.ToString("C"); } }

        //[Key]
        [Required]
        [MaxLength]
        public string PageURL { get; set; }

        [Required]
        [StringLength(250)]
        public string Name { get; set; }

        [Required]
        public string Code { get; set; }

        public string Description { get; set; }

        public int Category_ID { get; set; }

        [Column(TypeName = "money")]
        public decimal Price { get; set; }

        public DateTime? DateCreated { get; set; }

        public DateTime? DateModified { get; set; }

        [Required]        
        public bool Featured { get; set; }

        public virtual Category Category { get; set; }

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

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

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

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

Now I don't know if this is useful information, but the project started out as database first by mistake and then I changed it to code first because I figured that would be less confusing. I have tried a few different things and can't seem to figure it out.

UPDATE: Tried removing the product id from the bind statements and that still did not seem to resolve the issue. Here is what the bind statement was changed to.

  public ActionResult Create([Bind(Include = "PageURL,Name,Code,Description,Category_ID,Price,DateCreated,DateModified,Featured")] Product product)

UPDATE I have added a screenshot of my database schema. I tried adding the notmapped data annotation to that read only property as mentioned in comments below. It did not fix the exception. Am i missing something?

enter image description here

UPDATE: I have tried to make sure my schema matches, I added data annotations to the read only property to specify that it isn't mapped, and I still get this exception. I do not have enough reputation to put a bounty on this and I really need help figuring this issue out.

Upvotes: 1

Views: 528

Answers (1)

Joel Waymack
Joel Waymack

Reputation: 136

Without seeing your database schema, I'd wager that your model does not map correctly to the table it is based off of. Your property

public string FormattedPrice { get { return this.Price.ToString("C"); } }

is a derived property and cannot be mapped to a database field but you haven't told EF to ignore it. Try adding the [NotMapped] annotation to it. Likewise, check that all of your properties actually have corresponding fields in the database.

Feel free to post the table DDL statements for creation if you want more help identifying possible issues.

Upvotes: 1

Related Questions