代码之家  ›  专栏  ›  技术社区  ›  GoGo

在LINQ中包含带有WHERE子句的对象

  •  0
  • GoGo  · 技术社区  · 6 年前

    我希望有一个LINQ查询,它应该返回所有具有生命体征的成员,其中生命体征中的事件等于手术。

    我的 Member.cs 班级:

    public class Member
    {
        public int Id { get; set; }
        public string FullName { get; set; }
        public ICollection<VitalSign> VitalSigns { get; set; }
    
        public Member()
        {
             VitalSigns = new Collection<VitalSign>();
        }
    }
    

    还有我的 VitalSign.cs 类是:

    public class VitalSign
    {
        public int Id { get; set; }
        public string Event { get; set; }
    
        // relationships
        public Member Member { get; set; }
        public int MemberId { get; set; }
    }
    

    我写的LINQ查询是:

     return await context. Members.Include(c => c.VitalSigns.Where(t => t.Event == "post surgery")).ToListAsync();
    

    这将返回一个自引用循环。因为在 VitalSigns 如果事件不等于“术后”。我写的问题是错的吗?

    1 回复  |  直到 6 年前
        1
  •  4
  •   xanatos    6 年前

    查询应为:

    context.Members.Where(t => t.VitalSigns.Any(u => u.Event == "post surgery"))
        .Include(c => c.VitalSigns)
        .ToListAsync()
    

    这个 Include() 只提示在执行查询时应加载哪些表。

    查询类似于:

    all the members WHERE there is ANY (at least) one VitalSign with Event == post surgery
    together with the Members you'll get, please INCLUDE the VitalSigns (the alternative is that they'll be lazily loaded when you try to access them)
    return a List<> (ToListAsync) of the elements in an asynchronous way