Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
450 views
in Technique[技术] by (71.8m points)

EF Core circular relationship between two entities with onDelete(cascade and setNull)

I have trouble in EF Core using onDelete (cascade and setNull) with circular relationship. Here is my entities and configuration classes.

public class Customer 
{
        public int? DefaultCustomerAddressId { get; set; }
        public CustomerInvoiceAddress DefaultCustomerAddress { get; set; }
        public int No { get; set; }
        public string Name { get; set; }
}

public class CustomerInvoiceAddress : AuditableEntity
{
        public int? CustomerId { get; set; }
        public Customer Customer { get; set; }
        public string Address { get; set; }
}

public class CustomerConfiguration : AuditableEntityConfiguration<Customer>
{
        public override void Configure(EntityTypeBuilder<Customer> builder)
        {
           
            builder.HasOne(x => x.DefaultCustomerAddress).WithOne().HasForeignKey<Customer>(x => x.DefaultCustomerAddressId).OnDelete(Microsoft.EntityFrameworkCore.DeleteBehavior.ClientSetNull);

            base.Configure(builder);
        }
}

public class CustomerInvoiceAddressConfiguration:AuditableEntityConfiguration<CustomerInvoiceAddress>
    {
        public override void Configure(EntityTypeBuilder<CustomerInvoiceAddress> builder)
        {
            builder.HasOne(x => x.Customer).WithMany().OnDelete(Microsoft.EntityFrameworkCore.DeleteBehavior.Cascade);

            base.Configure(builder);
        }
    }

I am trying to, when user delete a customer also delete all related rows in CustomerInvoiceAddress entity (Cascade). When user delete a CustomerInvoiceAddress set null to related foreign key in Customer entity.(SetNull)

How do I do that? Or should I do that? Is a circular relationship acceptable? Is a circular relationship with cascade and setNull acceptable? Too many questions..

Sorry for my bad English.

question from:https://stackoverflow.com/questions/65945656/ef-core-circular-relationship-between-two-entities-with-ondeletecascade-and-set

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...