簡體   English   中英

ASP.Net MVC3 EF 4.1模型代碼第一個父級ID構造

[英]ASP.Net MVC3 EF 4.1 Model Code First Parent ID construct

我有這些課:

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。 我怎樣才能做到這一點?

如果我理解正確,您正在做類似的事情

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

並且您不希望所有 EventComments都加載,而只是特定的。

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

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM