Ignore duplicate key insert with Entity Framework

Since this is your primary key, your options are limited. If this wasn't your primary key, and just a unique index, assuming SQL Server, you could set up your unique key to ignore duplicates.

What I might suggest is to simply wrap a try/catch around the Add and eat the exception if the exception is a duplicate key error.

You might also see if your object supports the AddOrUpdate() method. I know this is supported in Code First implementations. I believe in this case it will do an add on a new or update if the row exists. However, this might still involve a trip to the DB to see if the user already exists in order to know whether to do an add or update. And, in some cases, you might not want to actually perform an update.

I think if it were me, I'd go the Try/Catch route.


You can do 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 will execute a single query in your database to find users which already exist, then filter them out of your NewUsers set.