0

In APS.NET Entity Framework I am specifying state_id as a Identity column and same as I have set it Auto-Incremented field in MySql Table. But when I perform insert operation it makes one more duplicate entries for the same data with different id. Here it is my code.

I has used [DatabaseGenerated(DatabaseGenerationOption.Computed)] property on state id to make it identity.

Hey guys I have just check it with break point and I found something very interesting, When 1st time I run this code add() method called two times but when I again refreshed page it called only single time. Please guide me what could be the issue with it?

Model :

public class state_model
{

    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    [Key]
    public int state_id { get; set;}
    public string state_name { get; set; }
}

Controller Action :

public ActionResult add()
    {
        DataLayer dal = new DataLayer();
        state_model st = new state_model();
        st.state_name = "Bihar";
        dal.states.Add(st);
        dal.SaveChanges();
        return View("View");
    }

Db Context :

public class DataLayer : DbContext
{
    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);
        modelBuilder.Entity<state_model>().ToTable("state_master");
    }

    public DbSet<state_model> states { get; set; }

}

DataBase Snapshot :

Database entries... View Snapshot:

record dislpayed in browser

Zala Krunal
  • 315
  • 1
  • 3
  • 17
  • So what is the question here? You want the state_name column to contain only unique values? – Teodor Kurtev Apr 01 '17 at 18:42
  • No problem is that whenever I insert data it adds two record for same data with different two IDs. @TeodorKurev – Zala Krunal Apr 01 '17 at 20:00
  • This code looks ok, are you sure the method is not called multiple times? – Cristian Szpisjak Apr 01 '17 at 20:36
  • Does some javascript method run twice? Maybe because of duplicate subscriptions or by [including packages twice](http://stackoverflow.com/a/18709664/861716). – Gert Arnold Apr 01 '17 at 22:08
  • Put a break point in `Add` method and see if that gets hit twice. If yes that means it's being called twice from the client. – Chetan Apr 02 '17 at 02:24
  • There are no javascript at cilent side because its just a method and i had hard coded state name in controller. but yes it seems it hits twice, how? that I am not able to figure out. @ChetanRanpariya – Zala Krunal Apr 02 '17 at 07:37
  • Hey guys I have just check it with break point and I found something very interesting, When 1st time I run this code add() method called two times but when I again refreshed page it called only single time. Please guide me what could be the issue with it? – Zala Krunal Apr 02 '17 at 07:44

0 Answers0