【问题标题】:Including an object with where clause in LINQ在 LINQ 中包含带有 where 子句的对象
【发布时间】:2018-05-21 19:35:17
【问题描述】:

我想要一个 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中有一些数据事件不等于“术后”。我是不是写错了查询?

【问题讨论】:

  • @RyanWilson 问题不在于顺序(WhereInclude 之前或之后),问题在于WhereInclude 应该在同一级别查询,所以Where外面的Include
  • @xanatos 感谢您的解释。感谢。我仍在使用 SQLClient 和存储过程等进行数据库工作。所以我对使用 Linq 语法的 EntityFramework 不是很熟悉。
  • @xanatos 如果他们在同一级别,那么我无法获得事件。
  • @gogo 因为你必须使用内部Any...查看我的回复

标签: sql linq .net-core


【解决方案1】:

查询应该是:

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

【讨论】:

  • 很好的解释,感谢您将其从 llambdas 分解为简单的 linq 语法。来自我的 +1。
  • 这个查询返回所有生命体征,无论事件是否等于“手术后”
  • @GoGo 它返回至少一个生命体征等于手术后的所有成员。包括其他生命体征。 It is a limitation of Entity Framework.
  • 好吧,目前无法过滤加载了哪些相关实体。包含将始终引入所有相关实体。那不好。msdn.microsoft.com/en-us/data/jj574232#explicitFilter
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-04-16
  • 2015-08-22
  • 1970-01-01
  • 2013-07-21
  • 1970-01-01
相关资源
最近更新 更多