Entity Framework Code first - FOREIGN KEY constraint problem

前端 未结 1 1441
礼貌的吻别
礼貌的吻别 2021-02-15 22:11

I\'m new to EF code first principal and currently with no clue what to do.. I have 2 POCO classes..

public class Problem
{
    public int ProblemID { get; set; }         


        
相关标签:
1条回答
  • 2021-02-15 22:55

    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.

    0 讨论(0)
提交回复
热议问题