Click here to Skip to main content
15,881,624 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
There are 2 tables:
public class Info
{
    [Key]
    public int id { get; set; }
    public int name { get; set; }
    public int surname { get; set; }
}


public class Client
{
    [Key]
    public int id { get; set; }
    [ForeignKey("info")]
    public int? infoId { get; set; }
    public virtual Info info { get; set }
}


How to configure ef core, so when Client is deleted, Info is deleted automatically? Something like cascade delete.

What I have tried:

Probably should be done in
OnModelCreating
somehow, but to this point I haven't figured it out.
Posted
Updated 3-Dec-20 3:36am

1 solution

Cascade Delete - EF Core | Microsoft Docs[^]

Assuming this is a one-to-one relationship[^]:
C#
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<Client>()
        .HasOne(c => c.info)
        .WithOne(i => i.client)
        .HasForeignKey<Client>(c => c.infoId)
        .OnDelete(DeleteBehavior.Cascade);
}
You'll need to add the reverse navigation property from Info to Client as well.
C#
public class Info
{
    public Client client { get; set; }
}
 
Share this answer
 
Comments
csrss 3-Dec-20 11:53am    
Unfortunately, this does not work

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900