Entity Framework, preventing duplication of records, simultaneous connections

If I use the entity framework as a backend for the MVC web API, one controller might look something like this (quick layout):

   public class PersonController : ApiController
   {
        [HttpPost]
        public void AddPerson(Person val)
        {
            DbContext context = new DbContext();
            if(!context.Persons.Any(x=>x.Email == val.Email))
            {
                context.Persons.Add(val)
                context.SaveChanges();
            }
        } 
   }

The problem is that if this operation was called 50, 100 times every few seconds (probably not a very good example), there is a high probability of adding multiple entries with the same email address.

If the parameter valwas a list Person, you can check changetrackerto see if someone has been added with an email address before you SaveChanges(), but this does not work when you have a lot of calls from different sources.

You cannot have a static one DBContext, as it will throw an exception, talking about its busyness.

, , , , ( ) DBContext, lock() , .

?

, , . , .

+4
3

, , , .

0

, . ? , . , "", ?

Email .

+1

put unique constraint index in email table? or change the SQL transaction isolation level to Serializable? or lock a static object so that one method can go through this method at a time?

http://msdn.microsoft.com/en-us/library/c5kehkcz.aspx

+1
source

Source: https://habr.com/ru/post/1530571/


All Articles