Duplicate pimary key while inserting Exception in MVC

When we generate the scaffolding templates from the existing model for creating read-write and edit.
We face an exception for the duplicate primary key if we do not provided primary key value.
So the Question Is how to autogenerate the next primary key value?

The answer is right here
1) Inside Create() Method Declare following Code.

 // GET: Products/Create
        public ActionResult Create()
        {
            Product product = new Product();
            product.Product_Id = db.Products.Max(item => item.Product_Id)+1;

            return View(product);
        }

 The red color code is newly added code.

And the next time if you see the value of the primary key will be auto-generated.

Comments

Popular posts from this blog

Code First Approach with Entity Framework

Getting Ready for Python Development on Ubuntu using VSCode

Designing Model class with validation in ASP.NET MVC