title: MVC Multithreaded server with entity framework object creation
body: <p>I have a POST action on my API that calls this function on an entity:</p>
  
  <pre><code>    Public Async Function MarkAsSeenBy(db As TaplomaV2Entities, user As User, Optional markAsComplete As Boolean = False, Optional save As Boolean = True) As Threading.Tasks.Task
  
      Dim userContent = Me.UserContents.SingleOrDefault(Function(uc) uc.UserID = user.UserID)
  
      If userContent Is Nothing Then
  
          userContent = New UserContent() With {
              .UserID = user.UserID,
              .FirstViewed = DateTime.Now,
              .LastViewed = DateTime.Now,
              .CourseContentID = Me.CourseContentID,
              .ViewCount = 1
          }
  
          If markAsComplete Then
              userContent.TimeCompleted = DateTime.Now
          End If
  
          db.UserContents.Add(userContent)
  
      Else
  
          userContent.ViewCount += 1
          userContent.LastViewed = DateTime.Now
  
          If markAsComplete Then
              userContent.TimeCompleted = If(userContent.TimeCompleted, DateTime.Now)
          End If
  
          db.Entry(userContent).State = EntityState.Modified
  
      End If
  
      If save Then
          Await db.SaveChangesAsync()
      End If
  
  End Function
  </code></pre>
  
  <p>Essentially it checks if it has a UserContent record associated with it, if not then it creates one and then increments the seen count and the time and so forth.</p>
  
  <p>Is this likely to create multiple records in the DB if the endpoint is called more than once?</p>
  
  <p>Since the server is threaded I would expect it to start checking on two different threads, both find no record and so both add a record which makes two records.</p>
  
  <p>What's the correct way to combat this kind of race condition with Entity Framework when creating new objects based on DB conditions?</p>