Home > DeveloperSection > Forums > Insert values to entity framework in asp.net mvc4
Chintoo Semi

Total Post:135

Points:947
Posted on    September-28-2013 3:55 AM

 ASP.NET MVC ASP.NET MVC 
Ratings:


 1 Reply(s)
 2523  View(s)
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.



Pravesh Singh
Pravesh Singh

Total Post:101

Points:709
Posted on    September-28-2013 6:31 AM

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

Don't want to miss updates? Please click the below button!

Follow MindStick