Avoid Adding Duplicate Records in ASP.NET using Entity Framework 5

So I have been playing around with ASP.NET Entity Framework 5, and I am a big fan of Code First development, especially the reverse engineering code first plugin, which you can learn about here.

However, this is not what this article will be about. I ran into an issue in which I had multiple types of users, however a single user could have multiple types (i.e. – Approver and Requestor). I was adding the users one type at a time, and in one scenario I was getting duplicate records being inserted. An example, Bob is a user who is not yet in the database. For a given request, Bob is designated as the Requestor, so I add him to the DB context. Later in code I determine that Bob is the Approver as well, so he again gets added to the DB Context. Upon reaching SaveChanges(), Bob gets inserted twice into the database. That’s not what I wanted.

The code below will remedy that scenario. I check the database for user Bob, but I will also check the current context to avoid adding Bob twice:

private Repository.Models.User GetUser(Repository.Models.DBContext db,
            string emailAddress)
        {
            var user = db.Users.FirstOrDefault(x => x.EmailAddress == emailAddress);

            if (user == null)
            {
                user = db.Users.Local.FirstOrDefault(x => x.EmailAddress == emailAddress);
            }

            return user;
        }

Questions or comments below.  Hope this adds some value for some 🙂

End of Line.

Advertisements

, , ,

  1. #1 by Steven Yates on March 7, 2014 - 04:37

    This doesn’t fix the problem of have multiple insertions from different DBContexts. If you use this in a web API you could have 50,100,1000 operations (which you cannot use the same DBContext).

  2. #2 by Onyximo on August 7, 2015 - 10:11

    Problem with this is if the table is empty initially it will insert

  3. #3 by reverse commissions free rotator on December 16, 2016 - 21:28

    Greetings! Very helpful advice on this article! It is the little changes that make the biggest changes. Thanks a lot for sharing!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: