2013-02-07 55 views
0

我有這些類:ASP.Net MVC3 EF 4.1型號代碼第一個父ID構建

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。 我該怎麼做?

回答

0

如果我理解正確的話,你在做類似

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

,你不希望加載的EventComments的所有,只是具體的。

不幸的是,EF沒有提供過濾.Include的機制。

但是,您可以使用預測如下概括:

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