Posts

Showing posts from June, 2019

Designing Model class with validation in ASP.NET MVC

The Generalized Example product model class. As given belowed. using System; // Using Data Annotation Library using System.ComponentModel.DataAnnotations; namespace modelDesigning.Models {     public class Product     {         // Product ID Decalration         // Key defines given Id is primary key         [Key]         // Required Annotation says its compulsory and required field.         [Required]         public int ProductID { get; set; }                         [Required]         // Max Length Annotation gives maximum length for string.         [MaxLength(50)]         public String ProductName { get; set; }         [Required]         public decimal Price { get; set; }         // Maximum length and minimum length of Description.         [MaxLength(100), MinLength(10)]         public string Product_Description { get; set; }     } }

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.