代码之家  ›  专栏  ›  技术社区  ›  Matthew Flynn

EntityTypeBuilder中的OnDelete<t>ASP.NET Core 2实体框架

  •  4
  • Matthew Flynn  · 技术社区  · 7 年前

    我使用下面的modelbuilder在数据库上设置我的关系。

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.HasDefaultSchema(schema: DbGlobals.SchemaName);
    
        modelBuilder.AddConfiguration<Address>(new AddressConfiguration());
        /*reduced for brevity*/
    
        base.OnModelCreating(modelBuilder);
    }
    

    在哪里 AddressConfiguration() 我有以下文件:

    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);
            }
        }
    }
    

    现在我的地址模型有 List<Contact> Contacts { get; set; } . 如何配置模型。要在删除地址时删除级联吗?

    我发现了以下联系;

    Delete Cascade in EF Core

    其中详细说明了 OnDelete 方法,但是在 EntityTypeBuilder<T> ?

    有人能告诉我我在这里做错了什么吗?

    1 回复  |  直到 7 年前
        1
  •  4
  •   user1672994    7 年前

    ondelete指定了当主体被删除或关系被断开时,应用于删除关系中的依赖实体时如何配置删除操作。

    它在referenceCollectionBuilder对象上可用。了解 here .

    解决方案

    你应该把这种关系定义为

    entity.HasMany(a => a.Contacts).WithOne(c => c.Address).OnDelete(DeleteBehavior.Cascade);