Entity Framework Code first - FOREIGN KEY constraint problem

前端 未结 1 1861
猫巷女王i
猫巷女王i 2021-02-15 22:04

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:50

    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 Users { get; set; }
        public DbSet Comments { get; set; }
        public DbSet Problems { get; set; }
    
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Entity()
                        .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)
提交回复
热议问题