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.
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
Post a Comment