Chris Hadfield
Chris Hadfield

Reputation: 524

Loading related data

I have a two table called Post and Comments where Post may contains many Comments. These are my model

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; }
  }

Now I want data Post data and its related comments. This is how I have implemented my service

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;
    }

And this is how I have configured my mappings

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);
    }

But this code doen't return me a comments. How can I achieve this approach Thanks.

Upvotes: 0

Views: 20

Answers (1)

Derviş Kayımbaşıoğlu
Derviş Kayımbaşıoğlu

Reputation: 30665

at first, you need to have public int PostId { get; set; } in Comment Class

can you try with this line?

builder.HasMany(p => p.Comments)
    .WithOne(p => p.Posts)
    .HasForeignKey(p => p.PostId);
    .OnDelete(DeleteBehavior.Cascade);

why dont you get results like this?

_dataContex.Posts.Include(p => p.Comments).ThenInclude(p => p.ApplicationUsers).FirstOrDefault(p => p.Id == id);

Upvotes: 1

Related Questions