Archive for category ASP.Net MVC

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.

, , ,


Attempted to read or write protected memory.

Before I begin, here is my setup:

  • Running Windows 7 Pro 64-bit inside a VirtualBox 4.0.4, the HOST operating system is Ubuntu 10.04.2
  • Microsoft Visual Studio 2010 Version 10.0.30319.1
  • Microsoft .NET Framework Version 4.0.30319

So folks, wtf does that error mean?

Just minding my own business, trying out some C# ASP.Net MVC3 tutorials, when BAMM! WACK! ZOW! I get this error: “Attempted to read or write protected memory. This is often an indication that other memory is corrupt.”

Attempted to read wright protected memory

I should mention it happens AT RANDOM.  I cannot narrow it down to one scenario that causes the issue.  I have also tried different MVC3 projects, and same thing occurs at random 😦

I tried to Google the issue, naturally, but no luck.  The most useful bit of advise I could find was to SWITCH TO IIS, instead of using Visual Studio Development Server.

Click here to see a screenshot for changing Visual Studio Project to use IIS.

This is a workaround that solved the issue for me, but if anyone knows the root cause please leave a comment.  I hate workarounds when I don’t know why they work.  But hey, I’m still going to use it 🙂

In the meantime, I hope this helps someone, cause I spent alot of time searching :/

End of Line.

, ,