简体   繁体   English

ASP.Net MVC3 EF 4.1模型代码第一个父级ID构造

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

i have these classes: 我有这些课:

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; }

}

In the context i have the following: 在上下文中,我有以下内容:

protected override void OnModelCreating(DbModelBuilder modelBuilder) 
 { 
     modelBuilder.Conventions.Remove<PluralizingTableNameConvention>(); 
     modelBuilder.Entity<EventComment>()
                 .HasMany(s => s.ChildComments)
                 .WithOptional()
                 .HasForeignKey(s => s.ParentCommentID);
 } 

The EventComments and children get loaded correctly. EventComments和子级将正确加载。 But every Event loads all EventComments with that EventID. 但是每个事件都使用该EventID加载所有EventComments。 The Event class should only load EventComments with no ParentID. Event类只能加载没有ParentID的EventComments。 How can i do that? 我怎样才能做到这一点?

If I understand correctly, you're doing something like 如果我理解正确,您正在做类似的事情

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

and you don't want all of the EventComments loaded, just specific ones. 并且您不希望所有 EventComments都加载,而只是特定的。

Unfortunately EF does not provide a mechanism to filter the .Include. 不幸的是,EF没有提供过滤.include的机制。

You can however use projections as outlined here: 但是,您可以使用此处概述的投影:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM