实体框架 (EF) 代码优先级联删除,用于一对零或一关系 [英] Entity Framework (EF) Code First Cascade Delete for One-to-Zero-or-One relationship

查看:31
本文介绍了实体框架 (EF) 代码优先级联删除,用于一对零或一关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

遵循Pluralsight入门"的代码优先建模"部分通过 Julie Lerman 的 Entity Framework 5" 课程,我创建了两个具有一对零或一关系的 POCO 类:一个父类(用户)和一个可选的 子级 (UserDetail).

Following the "Code First Modeling" section of the Pluralsight "Getting Started with Entity Framework 5" course by Julie Lerman, I created two POCO classes with a one-to-zero-or-one relationship: a parent (User) and an optional child (UserDetail).

User 和 UserDetail 数据模型图(点击查看).

注意图中的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() 方法时,不会删除数据库中的 User 记录,因为 UserDetail 中的外键没有启用级联删除.

When the Delete() method in the UserRepository class is called, it does not delete the User record in the database because the foreign key in UserDetail does not have cascade delete enabled.

DELETE 语句与 REFERENCE 约束FK_dbo.UserDetail_dbo.User_UserId"冲突.

The DELETE statement conflicted with the REFERENCE constraint "FK_dbo.UserDetail_dbo.User_UserId".

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

How would you enable cascading deletes for one-to-zero-or-one relationships using Entity Framework Code First (so that deleting a User automatically deletes UserDetail)?

推荐答案

您将必须使用 fluent API 来执行此操作.

You will have to use the fluent API to do this.

尝试将以下内容添加到您的 DbContext:

Try adding the following to your DbContext:

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

这篇关于实体框架 (EF) 代码优先级联删除,用于一对零或一关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆