title: Ignore duplicate key insert with Entity Framework
body: <p>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.</p>
  
  <p>I need to insert another 50 users. I might do this like</p>
  
  <pre><code>foreach(User user in NewUsers){
      context.Add(user);
  }
  dbcontext.SaveChanges();
  </code></pre>
  
  <p>The problem is, one or more of those new users might already exist in the DB. If I add them and then try to save, it throws an error and none of the valid ones get added. I could modify the code to do this:</p>
  
  <pre><code>foreach(User user in NewUsers){
      if(dbcontext.Users.FirstOrDefault(u =&gt; u.UserId) == null)
      {
          dbcontext.Users.Add(user);
      }
  }
  dbcontext.SaveChanges();
  </code></pre>
  
  <p>which would work. The problem is, then it has to run a query 50 times on a 200,000+ entry table. So my question is, what is the most performance efficient method of inserting these users, <strong><em>ignoring</em></strong> any duplicates?</p>