ASP.NET Core SQL Server connection - migrations

33 views Asked by At

I encounter this error when I use 2 different foreign keys.

Introducing FOREIGN KEY constraint 'FK_Comments_Posts_Id' on table 'Comments' may cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints.
Could not create constraint or index. See previous errors.

public class Comment
    {
        public int Id { get; set; }
        public int PostId{ get; set; }
        public Post Post { get; set; } = null!;
        public int UserId { get; set; }
        public AppUser User { get; set; } = null!;
    }

    public class AppDbContext : IdentityDbContext<AppUser,UserRole,int>
    {
        public AppDbContext(DbContextOptions<AppDbContext> options) : base(options)
        {
        }

        public DbSet<Comment> Comments { get; set; }
        public DbSet<Post> Posts { get; set; }

        protected override void OnModelCreating(ModelBuilder builder)
        {
            base.OnModelCreating(builder);
        }
    }

}


public class AppUser : IdentityUser


    {
    public List<Post> Posts { get; set; } = new List<Post>();
    public List<Comment> Comments { get; set; } = new List<Comment>();

}



  public class Post
{
    public int  Id { get; set; }
    public string Title { get; set; } = null!;
    public string Description { get; set; } = null!;
    public ICollection<Comment> Comments { get; set; }
    public string UserId {
        get;
        set;
    }
    public AppUser User { get; set; }
}
1

There are 1 answers

0
Aenye_Cerbin On

You should provide the rest of classes you reference. Also at the end of the error message there is the info to see the previous errors, they can also contain some info.

Do you have some other foreign keys in AppUser or Post?
Do you have some foreign key constraint or cascade behavior defined?

I guess in both of that classes you also have primary key ID, so you can simplify Comment class like that:

public class Comment {
    public int Id { get; set; }
    [ForeignKey("PostId")]
    public Post Post { get; set; } = null!;
    [ForeignKey("UserId")]
    public AppUser User { get; set; } = null!;
}