Dillanm
Dillanm

Reputation: 866

EFCore OnDelete Cascade many to one

I have a data model that is along the lines of:

public class Entity1
{
    public Guid Id { get; set; }
}

public class Entity2
{
    public Guid Id { get; set; }

    public Entity1 RelatedEntity { get; set; }
}

In my case there can be many Entity2s for each Entity1 but as far as I can tell it doesn't really make sense in my data mode to have Entity1 track all the Entity2s which use it. Maybe I am misunderstanding how data models are supposed to be built.

It seems (from the Microsoft tutorials) that in order to set up .OnDelete(DeleteBehavior.Cascade); you need to have a 2-way link between entities. Does anyone know if it is possible to do it such that if Entity1 is deleted it will take all Entity2 instances with it also? Will I have to change my data model such that Entity1 stores a list of Entity2's?

Thanks!

Upvotes: 2

Views: 287

Answers (1)

Ivan Stoev
Ivan Stoev

Reputation: 205629

None of the navigation properties is required.

All you need in order to configure a relationship is a correct pair of Has{One|Many} + With{One|Many}. By correct I mean the following - if the corresponding relationship end has navigation, it must be passed as argument, otherwise no lambda expression/property name should be passed).

i.e. in you case, you could use either

modelBuilder.Entity<Entity2>()
    .HasOne(e2 => e2.RelatedEntity)
    .WithMany() // no navigation property

or

modelBuilder.Entity<Entity1>()
    .WithMany<Entity2>() // no navigation property
    .HasOne(e2 => e2.RelatedEntity)

These are equivalent, use one or the another, neither both (to avoid conflicting configurations / discrepancies - after all, the relationship is just one, even though there are two ends).

Once you do that, you have access to relationship APIs for configuring the FK, cascade delete etc., e.g.

.OnDelete(DeleteBehavior.Cascade)

You could also make the FK required (which by default will turn cascade delete on):

.IsRequired()

For more info, see the Relationships section of the EF Core documentation, in particular Manual configuration and Single navigation property.

Upvotes: 1

Related Questions