Reputation: 3941
I use the following modelbuilder to setup my relationships on my database.
In my datacontext I have;
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.HasDefaultSchema(schema: DbGlobals.SchemaName);
modelBuilder.AddConfiguration<Address>(new AddressConfiguration());
/*reduced for brevity*/
base.OnModelCreating(modelBuilder);
}
where in the AddressConfiguration()
i have the following;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
namespace Data.EF.Configuration
{
internal class AddressConfiguration : DbEntityConfiguration<Address>
{
public override void Configure(EntityTypeBuilder<Address> entity)
{
entity.HasKey(x => x.Id);
entity.Property(x => x.Latitude).HasColumnType($"decimal(9,6)").IsRequired();
entity.Property(x => x.Longitude).HasColumnType($"decimal(9,6)").IsRequired();
//I have tried the following but it says doesnt exist
//entity.OnDelete(DeleteBehavior.Cascade);
}
}
}
Now my address model has a List<Contact> Contacts { get; set; }
. How can I configure the model. to delete cascade on when the Address is deleted?
I found the following link;
Which is detailing an OnDelete
method, however this doesnt seem to be present on the EntityTypeBuilder<T>
?
Can anyone tell me what I am doing wrong here please?
Upvotes: 4
Views: 6225
Reputation: 10849
OnDelete
specifies how to configure delete operation when applied to delete the dependent entities in the relationship when the principal is deleted or the relationship is severed.
It is available on ReferenceCollectionBuilder
|ReferenceReferenceBuilder
objects. Read about here.
Solution
You should define the relationship as
entity
.HasMany(a => a.Contacts)
.WithOne(c => c.Address)
.OnDelete(DeleteBehavior.Cascade);
Upvotes: 6