EF Core / Sqlite one-to-many relationship failing on Unique Index Constraint

后端 未结 2 392
花落未央
花落未央 2021-01-14 03:21

The context is each Car has a corresponding CarBrand. Now my classes are as shown below:

public class Car
{
    public int CarId {          


        
2条回答
  •  梦谈多话
    2021-01-14 03:33

    The problem is that Add method cascades:

    Begins tracking the given entity, and any other reachable entities that are not already being tracked, in the Added state such that they will be inserted into the database when SaveChanges is called.

    There are many ways to achieve the goal, but the most flexible (and I guess the preferred) is to replace the Add method call with the ChangeTracker.TrackGraph method:

    Begins tracking an entity and any entities that are reachable by traversing it's navigation properties. Traversal is recursive so the navigation properties of any discovered entities will also be scanned. The specified callback is called for each discovered entity and must set the State that each entity should be tracked in. If no state is set, the entity remains untracked. This method is designed for use in disconnected scenarios where entities are retrieved using one instance of the context and then changes are saved using a different instance of the context. An example of this is a web service where one service call retrieves entities from the database and another service call persists any changes to the entities. Each service call uses a new instance of the context that is disposed when the call is complete. If an entity is discovered that is already tracked by the context, that entity is not processed (and it's navigation properties are not traversed).

    So instead of context.Cars.Add(car2); you could use the following (it's pretty generic and should work in almost all scenarios):

    context.ChangeTracker.TrackGraph(car2, node =>
        node.Entry.State = !node.Entry.IsKeySet ? EntityState.Added : EntityState.Unchanged);
    

提交回复
热议问题