Can we get concurrency errors for multiple entities in EF Core?

Yossu 11 Reputation points
2022-05-01T16:11:55+00:00

All the info I've seen on handling concurrency errors in EF Core (for example, the MS docs page https://learn.microsoft.com/en-us/ef/core/saving/concurrency) only show how to handle the case where a single entity has a concurrency error.

What happens if you try to save an object graph, and more than one entity in the graph has been updated since you got your copy.

For example, using the sample code on that MS page, if you change the models so that the Person has a Pet...

public class Person {  
  public int PersonId { get; set; }  
  [ConcurrencyCheck]  
  public string FirstName { get; set; }  
  [ConcurrencyCheck]  
  public string LastName { get; set; }  
  public string PhoneNumber { get; set; }  
  [ConcurrencyCheck]  
  public Pet Pet { get; set; }  
}  
  
public class Pet {  
  public int Id { get; set; }  
  [ConcurrencyCheck]  
  public string Name { get; set; }  
}  

...and add a Pets property to the context, then you can try grabbing a person with their pet, then updating both, and also simulating someone else updating both...

var person = context.People.Include(p => p.Pet).Single(p => p.PersonId == 1);  
person.PhoneNumber = "555-555-5555";  
person.Pet.Name = "Frederick";  
  
context.Database.ExecuteSqlRaw("UPDATE dbo.People set FirstName = 'Fred' WHERE PersonId = 1");  
context.Database.ExecuteSqlRaw("UPDATE dbo.Pets set Name = 'Fred' WHERE Id = 1");  

However, the ex.Entries object only has info about one of the entities, not both.

Is it possible to get info about every entity that had a concurrency error?

Thanks

Entity Framework Core
Entity Framework Core
A lightweight, extensible, open-source, and cross-platform version of the Entity Framework data access technology.
764 questions
{count} votes

1 answer

Sort by: Most helpful
  1. AgaveJoe 28,876 Reputation points
    2022-05-03T19:15:12.37+00:00

    Seems odd that the exception has an Entries property, if you can only ever get one property.

    Pet is a navigation property - a different table. Typically a transaction is rolled back on the first problem. Execution does not continue trying to do updates to other tables when the transaction has already failed.

    What is the use case you are trying to solve?

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.