ASP.Net EF identity column issue, Duplicate entries on single operation

随声附和 提交于 2019-12-20 06:15:03

问题


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 :

View Snapshot:

来源:https://stackoverflow.com/questions/43160455/asp-net-ef-identity-column-issue-duplicate-entries-on-single-operation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!