Posts Tagged c#

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.


, , ,