0

我有这些课程:

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。我怎样才能做到这一点?

4

1 回答 1

0

如果我理解正确,你正在做类似的事情

var event = (from e in ctx.Event.Include(p=>p.EventComment) select e);

并且您不希望加载所有EventComments,只需要加载特定的 EventComments。

不幸的是,EF 没有提供过滤 .Include 的机制。

但是,您可以使用此处概述的投影:

https://stackoverflow.com/a/5666403/141172

于 2013-02-07T17:16:12.013 回答