EF Core delete on table violates foreign key constraint on table

Viewed 8267

I have two tables (Device and PropertyValue) and when I try to delete a Device I get an exception saying:

violates foreign key

I also tried to set the cascade on OnModelCreating(), but still not work.

public class Device
{
    public int Id { get; set; }
    public List<PropertyValue> Properties { get; set; }
}

public class PropertyValue
{
    public int Id { get; set; }
    public int? DeviceId { get; set; }
    public Device Device { get; set; }
}

modelBuilder.Entity<PropertyValue>()
    .HasOne(p => p.Device)
    .WithMany(b => b.Properties)
    .HasForeignKey(w => w.DeviceId)
    .OnDelete(DeleteBehavior.Cascade);  

EDIT: I am using a repository but basally I am deleting using _context.Devices.Remove(entity);

2 Answers

Since the FK property DeviceId is nullable, the relationship is optional, which by default has delete cascade turned off.

So adding .OnDelete(DeleteBehavior.Cascade) is step in the right direction.

But if you haven't done that initially and have already created your tables and relationships, you have to make sure it's applied in the database as well (because for cascade delete EF relies in general to be implemented by the database), by generating new migration and updating the database.

Related