Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EF Core - Error when adding a related entity

I get an error when I try to update a related entity of an entity that I already got from database. For illustration purposes I have these entites:

    class Car
{
   int Id ..;
   string Name ..;
   virtual ICollection<TireCar> tires ...;
}

class TireCar
{
  int Id ..;
  int TireId ..;
  int CarId..;
  int Size..;
  virtual TireBrand tire;
  virtual Car car;
}

class TireBrand
{
  int Id;
  string Name ..;
}

So, I'm trying to make a Patch method that allows me to update the Car data and also adds, updates or deletes the tires. The problem happens when I get the Car entity and after that I add a Tire. Something like that:

    void UpdateCar()
    {
        var car = carService.Get(...);

        ...

        carService.AddTire(new TireCar{ CarId = car.Id, TireId = 1 });

        ...
    }

I'm using the Repository pattern with DI, so the context is the same. The error that is throwing is:

System.InvalidOperationException: The association between entity types 'Car' and 'TireCar' has been severed but the foreign key for this relationship cannot be set to null. If the dependent entity should be deleted, then setup the relationship to use cascade deletes.'

I tried two things that worked but I think is not the solution:

  • When I get the Car after adding the Tires
  • When I get the Car as no tracking

Why that happend if I'm updating another tables? What Can I do to solve this?

like image 364
Gabriel Castillo Prada Avatar asked Sep 04 '17 16:09

Gabriel Castillo Prada


People also ask

How you can load related entities in EF?

Entity Framework supports three ways to load related data - eager loading, lazy loading and explicit loading. The techniques shown in this topic apply equally to models created with Code First and the EF Designer.

What is DbSet in Entity Framework Core?

In Entity Framework Core, the DbSet represents the set of entities. In a database, a group of similar entities is called an Entity Set. The DbSet enables the user to perform various operations like add, remove, update, etc. on the entity set.


1 Answers

Your issue is actually a configuration issue, not an issue with EF Core. Read carefully what the error says:

The association between entity types 'Car' and 'TireCar' has been severed but the foreign key for this relationship cannot be set to null. If the dependent entity should be deleted, then setup the relationship to use cascade deletes.

Entity Framework Core has by default (.NET Core 2.0 forward) a SET NULL policy when a dependent entity becomes orphan. If we look carefully at your TireCar model, you are not setting the CarId property as nullable, so the column cannot be set to null.

You have two different solutions to fix this. If you want the TireCar entity to get deleted when you remove it from your Car entity, then setup cascade deletes for this relationship (You can also change the EF Core default policy). This can be setup in your DbContext via FluentApi.

class MyContext : DbContext
{
    // Your DbSets

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<TireCar>()
            .HasOne(tc => tc.car)
            .WithMany(car => car.tires)
            .OnDelete(DeleteBehavior.Cascade);
    }
}

Another solution is to let the TireCar entity have null values in the CarId column, simply changing your entity model like this.

class TireCar
{
    public int Id  { get; set; }
    public int TireId { get; set; }
    public int? CarId { get; set; }
    public int Size { get; set; }
    public virtual TireBrand tire { get; set; }
    public virtual Car car { get; set; }
}
like image 73
jorgonor Avatar answered Sep 27 '22 23:09

jorgonor