0

My classes:

public class Post : Entity
{
    public bool Active { get; set; }

    public IList<Comment> Comments { get; set; }
    public IList<Category> Categories { get; set; }

    public Post ()
    {
         Categories = new List<Category>();            
         Comments = new List<Comment>();
    }
}

public class Comment: Entity
{
    public string UserName { get; set; }
    public CommentStatus Status { get; set; }

    public int PostId { get; set; }
    public Post Post { get; set; }
}

public class Category: Entity
{
    public string Name { get; set; }

    public IList<Post> Posts { get; set; }

    public Category()
    {
        Posts= new List<Post>();
    }
}

My mapping:

public class PostMap: EntityTypeConfiguration<Post>
{
    public PostMap()
    {
        ToTable("Posts");

        HasKey(x => x.Id)
       .Property(x => x.Id)
       .HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);

        HasMany(x => x.Categories)
        .WithMany(x => x.Posts)
        .Map(x =>
        {
            x.MapLeftKey("PostId");
            x.MapRightKey("CategoryId");
            x.ToTable("PostXCategory");
        });

        HasMany(x => x.Comments)
        .WithRequired(x => x.Post)
        .HasForeignKey(x => x.PostId);
    }
}

public class CategoryMap: EntityTypeConfiguration<Category>
{
    public CategoryMap()
    {
        ToTable("Categories");

        HasKey(x => x.Id)
       .Property(x => x.Id)
       .HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
    }
}

and finally my projection:

var query = _sqlRepository.Query<Post>()
.Where(x => x.Active)
.Select(x => new
{
    Post = x,
    Categories = x.Categories.ToList(),
    Comments = x.Comments.Where(c => c.Status == CommentStatus .Approved).ToList()
});

var data = query.ToList();

The problem is that eager loading is not working for "Categories", just for "Comments".

When I check my projection (var data), I see this:

enter image description here

But when I select "Post" (data.Select(x => x.Post)) the Categories is empty:

enter image description here

Why Categories is empty and comments not?

MuriloKunze
  • 15,195
  • 17
  • 54
  • 82
  • 1
    That's because relationship fixup doesn't work for many-to-many associations. The best explanation you can get for this is given [here](http://stackoverflow.com/questions/20919303/how-to-manually-load-related-entities-in-a-nn-relationship/20920753#20920753), so I won't try to improve it. – Gert Arnold Nov 23 '16 at 22:06
  • @GertArnold thank you. – MuriloKunze Nov 23 '16 at 22:24

0 Answers0