У меня есть две таблицы с именами Post
и Comments
, где Post
может содержать множество Comments
.Это моя модель
public class Post
{
public int Id { get; set; }
public string PostText { get; set; }
public string Title { get; set; }
public bool Status { get; set; }
public DateTime PostDate { get; set; }
public virtual List<Comment> Comments { get; set; }
public virtual ApplicationUser ApplicationUser { get; set; }
}
public class Comment
{
public int Id { get; set; }
public string CommentText { get; set; }
public DateTime CommentTime { get; set; }
public bool Status { get; set; }
public virtual ApplicationUser ApplicationUsers { get; set; }
public virtual Post Posts { get; set; }
}
Теперь я хочу данные Опубликовать данные и связанные с ними комментарии.Вот как я реализовал свой сервис
public Post GetPostById(int id)
{
var result = _dataContext.Set<Post>().Include(p => p.Comments).ThenInclude(p => p.ApplicationUsers).FirstOrDefault(p => p.Id == id);
return result;
}
И вот как я настроил свои отображения
public void Configure(EntityTypeBuilder<Post> builder)
{
builder.HasKey(p => p.Id);
builder.Property(p => p.PostText).IsUnicode(true).IsRequired(true).HasMaxLength(9999);
builder.Property(p => p.Title).IsUnicode(true).IsRequired().HasMaxLength(100);
builder.Property(p => p.PostDate).HasDefaultValue(DateTime.Now).IsRequired(true);
builder.Property(p => p.Status).HasDefaultValue(true).IsRequired(true);
builder.HasMany(p => p.Comments)
.WithOne(p => p.Posts)
.OnDelete(DeleteBehavior.Cascade);
builder.HasOne(p => p.ApplicationUser)
.WithMany(p => p.Posts);
}
Но этот код не возвращает мне комментарии.Как я могу достичь этого подхода Спасибо.