EF Core delete on table violates foreign key constraint on table

c# entity-framework-core

Question

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);

1
1
10/25/2018 7:37:27 AM

Accepted Answer

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.

2
10/25/2018 9:04:16 AM

Popular Answer

If the related entities in the Properties collection are not loaded and tracked by the context, they will not be deleted. The recommended approach is to set a cascade action on the foreign key constraint in the database as well, as described in the documentation for DeleteBehavior:

https://docs.microsoft.com/en-us/ef/core/api/microsoft.entityframeworkcore.metadata.deletebehavior

If you create the schema automatically with EF, this is also what will be generated.



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow