Ignore duplicate key insert with Entity Framework

后端 未结 5 445
遇见更好的自我
遇见更好的自我 2020-12-29 03:36

I\'m using ASP.NET MVC4 with Entity Framework Code First. I have a table called \"users\", with primary key \"UserId\". This table may have 200,000+ entries.

I need

5条回答
  •  隐瞒了意图╮
    2020-12-29 04:04

    You can just filter out the failures and keep trying until it succeeds or you get another sort of Exception

    public partial class YourEntities: DbContext
    {
        public override int SaveChanges()
        {
            var isSaved = false;
            do
            {
                try
                {
                    return base.SaveChanges();
                }
                catch (DbUpdateException ex)
                {
                    var entries = ex.Entries;
                    foreach (var entry in entries)
                    {
                        // change state to remove it from context 
                        entry.State = EntityState.Detached;
                    }
                }
            }
            while (!isSaved);
    
            return null;    // never gets here
        }
    }
    

    You might want to put in some extra logic to avoid an infinite loop.

提交回复
热议问题