entity framework(EF)代码第一级联删除的一对零或一的关系

继Julie Lerman的Pluralsight“Entity Framework 5入门”课程的“代码优先build模”部分之后,我创build了两个具有一对一或一对一关系的POCO类:一个父代(User)和一个可选孩子(UserDetail)。

用户和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()方法时,它不会删除数据库中的用户logging,因为UserDetail中的外键没有启用级联删除。

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

你将如何使用entity framework代码优先级(以便删除用户自动删除UserDetail)启用级联删除一对零或一个关系

你将不得不使用stream利的API来做到这一点。

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

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

此代码为我工作

 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中)