Here are my models:
public class Post
{
[Key]
public int PostId { get; set; }
[Required]
[MaxLength(140)]
public string Title { get; set; }
[Required]
public string ApplicationUserId { get; set; }
public ApplicationUser ApplicationUser { get; set; }
public ICollection<Comment> Comments { get; set; }
}
public class Comment
{
[Key]
public int CommentId { get; set; }
[Required]
[StringLength(1000)]
public string Text { get; set; }
[Required]
public int PostId { get; set; }
[Required]
public string ApplicationUserId { get; set; }
public Post Post { get; set; }
public ApplicationUser ApplicationUser { get; set; }
}
I get an error message:
Representation of the FOREIGN KEY constraint "FK_Comment_Post_PostId" in the "Comment" table can cause loops or several cascading paths. Specify ON DELETE NO ACTION or ON UPDATE NO ACTION or change other FOREIGN KEY constraints. Failed to create constraint or index. See Previous Errors.
This is what is demonstrated in the documents .
Now if I remove:
[Required]
public int PostId { get; set; }
and use the Fluent API as follows:
builder.Entity<Comment>().HasOne(p => p.Post).WithMany(c => c.Comments).IsRequired();
I still get the same error. If I explicitly state
builder.Entity<Comment>().HasOne(p => p.Post).WithMany(c => c.Comments).IsRequired().OnDelete(DeleteBehavior.Cascade);
I still get the same error.
If I use the following:
builder.Entity<Comment>().HasOne(p => p.Post).WithMany(c => c.Comments);
Comment can be entered without message. The comment must belong to the message.
- ? , 1 FK .