c# - Ignore duplicate key insert with Entity Framework -
i'm using asp.net mvc4 entity framework code first. have table called "users", primary key "userid". table may have 200,000+ entries.
i need insert 50 users. might like
foreach(user user in newusers){ context.add(user); } dbcontext.savechanges();
the problem is, 1 or more of new users might exist in db. if add them , try save, throws error , none of valid ones added. modify code this:
foreach(user user in newusers){ if(dbcontext.users.firstordefault(u => u.userid) == null) { dbcontext.users.add(user); } } dbcontext.savechanges();
which work. problem is, has run query 50 times on 200,000+ entry table. question is, performance efficient method of inserting these users, ignoring duplicates?
you can this:
var newuserids = newusers.select(u => u.userid).distinct().toarray(); var usersindb = dbcontext.users.where(u => newuserids.contains(u.userid)) .select(u => u.userid).toarray(); var usersnotindb = newusers.where(u => !usersindb.contains(u.userid)); foreach(user user in usersnotindb){ context.add(user); } dbcontext.savechanges();
this execute single query in database find users exist, filter them out of newusers
set.
Comments
Post a Comment