我有这些课程:
public class Event
{
[Key]
public int ID { get; set; }
[Required]
public string Name { get; set; }
[Required]
public DateTime Begin { get; set; }
[Required]
public DateTime End { get; set; }
public string Description { get; set; }
public virtual ICollection<EventRegistration> Registrations { get; set; }
public virtual ICollection<EventComment> Comments { get; set; }
}
public class EventComment
{
[Key]
public int ID { get; set; }
[Required]
public int PersonID { get; set; }
[Required]
public int EventID { get; set; }
[Required]
public DateTime EntryDate { get; set; }
[Required]
public string Comment { get; set; }
public int? ParentCommentID { get; set; }
public virtual Event CommentEvent { get; set; }
public virtual Person CommentPerson { get; set; }
public virtual EventComment ParentComment { get; set; }
public virtual ICollection<EventComment> ChildComments { get; set; }
}
在上下文中,我有以下内容:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
modelBuilder.Entity<EventComment>()
.HasMany(s => s.ChildComments)
.WithOptional()
.HasForeignKey(s => s.ParentCommentID);
}
EventComments 和子项被正确加载。但是每个事件都会加载具有该 EventID 的所有 EventComments。Event 类应该只加载没有 ParentID 的 EventComments。我怎样才能做到这一点?