Remove entity from joint table without affecting parent - EF Core 2.2

216 Views Asked by At

I have an issue with many-to-many relationship, and I do not understand why it is behaving this way:

so I have the following:

public class A 
{
    public Guid Guid { get; set; }
    
    public ICollection<AB> ABs { get; set; }
}
public class B 
{
    public Guid Guid { get; set; }
    
    public ICollection<AB> ABs { get; set; }
}
public class AB 
{
    public Guid Guid { get; set; }
    public A A { get; set; }
    public Guid A_Id { get; set; }
    public B B { get; set; }
    public Guid B_Id { get; set; }

    internal static void OnModelCreating(ModelBuilder builder)
    {
        builder.Entity<AB>(entity =>
        {
            entity.HasIndex(e => new { e.A_Id, e.B_Id}).IsUnique();

            entity.HasOne(e => e.A)
                .WithMany(p => p.ABs)
                .HasForeignKey(e => e.A_Id)
                .OnDelete(DeleteBehavior.Restrict);
                
            entity.HasOne(e => e.B)
                .WithMany(w => w.ABs)
                .HasForeignKey(e => e.B_Id)
                .OnDelete(DeleteBehavior.Restrict);
            });
        }
}

I am keep getting:

The association between entity types 'A' and 'AB' has been severed but the relationship is either marked as 'Required' or is implicitly required because the foreign key is not nullable. If the dependent/child entity should be deleted when a required relationship is severed, then setup the relationship to use cascade deletes. Consider using 'DbContextOptionsBuilder.EnableSensitiveDataLogging' to see the key values.

Issue is that I want to break the relationship, by deleting AB from A.ABs, and EF Core tries to delete A. I do not understand what's going on. Any ideas?

Best regards

1

There are 1 best solutions below

2
Serge On

Why did you put on modelcreating inside of AB class? It should be inside of dbcontext.

And try add a key to you AB class too. Since you are using v.2.2 it will make EF more relaible.

public class A 
{
    public Guid Id{ get; set; }
    
    public ICollection<AB> ABs { get; set; }
}
public class B 
{
    public Guid Id { get; set; }
    
    public ICollection<AB> ABs { get; set; }
}
public class AB 
{   
    public Guid Id { get; set; }    
    public A A { get; set; }
    public Guid A_Id { get; set; }
    public B B { get; set; }
    public Guid B_Id { get; set; }
}