【问题标题】:EF Code First - Collection within CollectionEF Code First - 集合中的集合
【发布时间】:2012-11-14 00:09:17
【问题描述】:

我可能是个白痴,过去 2 小时我一直在寻找这个问题的答案,问题可能是我不确定如何表达它。

基本上我是第一次编写代码并在这个项目中使用它并且不确定如何查询它。

我有三门课

个人资料 > 团队 > 活动

我需要获取特定用户可以访问的事件列表,该用户必须是拥有该事件的团队的成员。

一个用户(个人资料)可以是多个团队的成员,我需要一份来自所有团队的事件列表。

我已经减少了我的课程,因为其中大部分与我目前的要求无关

  private void BindEvents()
    {
        var db = new Context();

        var events = db.Profiles
            .Include("Teams")
            .Include("Teams.Events")
            .Where(p => p.User_ID == user)
            .FirstOrDefault().Teams.Select(t => new { t.Events }.Events);

        gvUpcomingEvents.DataSource = events;
        gvUpcomingEvents.DataBind();

        db.Dispose();
    }

public class Profile
{
   [Key]
   public Guid User_ID { get; set; }
   [Required, MaxLength(10)]
   public string Title { get; set; }
   [Required, MaxLength(50)]
   public string Forename { get; set; }
   [Required, MaxLength(50)]
   public string Surname { get; set; }
   public ICollection<Team> Teams { get; set; }
   public Profile()
   {
       Teams = new HashSet<Team>();
   }
}


public class Team
{
    [Key]
    public int ID { get; set; }
    [Required, MaxLength(150)]
    public string Name { get; set; }
    [Required]
    public bool Active { get; set; }

    //Foreign Keys
    public ICollection<Profile> Users { get; set; }
    public ICollection<Event> Events { get; set; }

    public Team()
    {
        Users = new HashSet<Profile>();
    }
}

public class Event
{
   [Key]
   [Required]
   public int ID { get; set; }
   [Required]
   public Guid GUID { get; set; }
}

【问题讨论】:

    标签: c# asp.net entity-framework code-first


    【解决方案1】:

    试试 SelectMany

    var events = db.Profiles
             .Where(p => p.User_ID == user)
             .SelectMany(p=>p.Teams.SelectMany(t=>t.Events));
    

    【讨论】:

    • 谢谢,早上上班会试试这个,告诉你进展如何。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-04-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多