INSERT VALUES TO ENTITY FRAMEWORK IN ASP.NET MVC4

Chintoo Semi

Total Post:135

Points:947
Posted by  Chintoo Semi
 3020  View(s)
Ratings:
Rate this:

In my asp.net mvc4 sample i have table in the name of Sample with three column as Name,Dept and Id.In this Id as identity and primary.I get a value for Name and Dept from user and insert that value to Sample table of entity framework.It pass value '0' to Id.And i got an error as "Store update, insert, or delete statement affected an unexpected number of rows (0). Entities may have been modified or deleted since entities were loaded. Refresh ObjectStateManager entries".

Please help me.

  1. Pravesh Singh

    Post:101

    Points:709
    Re: Insert values to entity framework in asp.net mvc4

    Hey Chintoo!

    In EF code-first this is done by data annotations. Make sure you recreate your table (or database) after changing the scheme.

    public class Sample

    {

        [Key]

        [Required]

        [Column(Order = 0)]

        [DatabaseGenerated(DatabaseGeneratedOption.Identity)] //auto increment id

        public int Id { get; set; }

        [Required]

        public string Name { get; set; }

        [Required]

        public int Dept { get; set; }

    }

    You don't need to pass an integer for Id. EF will resolve this automatically. Just create the object by filling in the name and the dept. By saving the changes to the database, EF will automatically fill in the auto generated Id.

      Modified On Apr-12-2016 12:11:45 AM

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!