实体框架(EF)代码优先级联删除一对一或零关系

时间:2013-07-05 11:13:56

标签: c# entity-framework ef-code-first entity-framework-5 cascading-deletes

Pluralsight "Getting Started with Entity Framework 5" course by Julie Lerman的“Code First Modeling”部分之后,我创建了两个POCO类,其中一对一或一个关系:父(User)和可选子级(UserDetail)。

User and UserDetail data model diagram (click to view).

请注意,图中 UserId属性是主键,UserDetail是的外键。

相关代码:

public class User
{
    //...

    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int UserId { get; set; }

    /* Has a 1:0..1 relationship with UserDetail */
    public virtual UserDetail UserDetail { get; set; }

    //...
}

public class UserDetail
{
    //...

    /* Has a 0..1:1 relationship with User */
    public virtual User User { get; set; }

    [Key, ForeignKey("User")]
    public int UserId { get; set; }

    //...
}

public class EFDbContext : DbContext
{
    public DbSet<User> Users { get; set; }
    //public DbSet<UserDetail> UserDetails { get; set; }  /* Explicit declaration not necessary. Context is aware of UserDetail entity due to 0..1:1 relationship with User */

    public EFDbContext()
    {
        Configuration.ProxyCreationEnabled = true;
        Configuration.LazyLoadingEnabled = true;
    }
}

public class UserRepository : IUserRepository
{
    private EFDbContext _context = new EFDbContext();

    public void Delete(User entity)
    {
        entity = _context.Users.Find(entity.UserId);

        //...

        _context.Users.Remove(entity);
        _context.SaveChanges();

        //...
    }
}

当调用UserRepository类中的Delete()方法时,它不会删除数据库中的用户记录,因为UserDetail中的外键没有启用级联删除。

  

DELETE语句与REFERENCE约束“FK_dbo.UserDetail_dbo.User_UserId”冲突。

如何使用实体框架代码优先启用一对一或一对关系的级联删除(以便删除用户自动删除UserDetail)?

3 个答案:

答案 0 :(得分:70)

您必须使用流畅的API来执行此操作。

尝试将以下内容添加到DbContext

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{   
    modelBuilder.Entity<User>()
        .HasOptional(a => a.UserDetail)
        .WithOptionalDependent()
        .WillCascadeOnDelete(true);
}

答案 1 :(得分:3)

您还可以通过执行以下操作在应用程序的全局范围内禁用级联删除约定:

modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>()
modelBuilder.Conventions.Remove<ManyToManyCascadeDeleteConvention>()

答案 2 :(得分:1)

这段代码对我有用

protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<UserDetail>()
            .HasRequired(d => d.User)
            .WithOptional(u => u.UserDetail)
            .WillCascadeOnDelete(true);
    }

迁移代码是:

public override void Up()
    {
        AddForeignKey("UserDetail", "UserId", "User", "UserId", cascadeDelete: true);
    }

它工作正常。我第一次使用时

modelBuilder.Entity<User>()
    .HasOptional(a => a.UserDetail)
    .WithOptionalDependent()
    .WillCascadeOnDelete(true);

迁移代码是:

AddForeignKey("User", "UserDetail_UserId", "UserDetail", "UserId", cascadeDelete: true); 

但它与两个可用的任何重载都不匹配(在EntityFramework 6中)