本文介绍了实体框架(EF)code首先级联删除一至零或一的关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 29岁程序员,3月因学历无情被辞! 继code首先模拟的部分Pluralsight朱莉·勒曼开始使用实体框架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). 用户和UserDetail数据模型图(点击查看)。这图中的注意事项UserID属性是一个主键和UserDetail外键相关code: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类删除()方法被调用,它不会删除用户记录在数据库中,因为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语句冲突与基准约束FK_dbo.UserDetail_dbo.User_UserId。 The DELETE statement conflicted with the REFERENCE constraint "FK_dbo.UserDetail_dbo.User_UserId".你会如何启用级联删除一到零或一对一的关系使用实体框架code首先(以便删除用户将自动删除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)?推荐答案您将不得不使用流畅API来做到这一点。You will have to use the fluent API to do this.尝试添加下面您的数据库上下文Try adding the below to your DB Context protected override void OnModelCreating(DbModelBuilder modelBuilder) { modelBuilder.Entity<User>() .HasOptional(a => a.UserDetail) .WithOptionalDependent() .WillCascadeOnDelete(true);} 这篇关于实体框架(EF)code首先级联删除一至零或一的关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云! 06-05 01:58