首页 > 解决方案 > 在 LINQ 中包含带有 where 子句的对象

问题描述

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

我的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的事件不等于“术后”。我写错了查询吗?

标签: sqllinq.net-core

解决方案


查询应该是:

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

推荐阅读