我的课程:
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>();
}
}
我的映射:
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);
}
}
最后我的预测:
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();
问题是急切加载不适用于“类别”,仅适用于“评论”。
当我检查我的投影(var数据)时,我看到了:
但是当我选择“发布”(data.Select(x => x.Post)
)时,类别为空:
为什么类别为空而评论不是?