Entity Framework Code first - FOREIGN KEY constraint problem

霸气de小男生 提交于 2019-12-03 12:49:17

That will be because of Comments. EF by default uses cascade deletes on references. In your case the cascade delete will be created from User -> Problem, User -> Comment but also from Problem -> Comment. If you deleted User cascading to the same comment record can come from both Problem and User. That is not allowed in SQL Server. Each record can be accessible by only single cascade delete path.

To avoid this you must use fluent mapping to turn of cascade delete on one relation (you must make choice which one). The example for User -> Comment

public class Context : DbContext
{
    public DbSet<User> Users { get; set; }
    public DbSet<Comment> Comments { get; set; }
    public DbSet<Problem> Problems { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<User>()
                    .HasMany(u => u.Comments)
                    .HasRequired(c => c.User)
                    .HasForeignKey(c => c.UserId)
                    .WillCascadeOnDelete(false);

        base.OnModelCreating(modelBuilder);
    }
} 

There can be other entities and relations which can cause this problem in your model but Comment looks obvious from your example.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!