简体   繁体   English

在子实体上实现 where 子句的 Linq 查询 - EF Core

[英]Linq query to implement where clause on child entities - EF Core

What I'm trying to do should be really easy, but I just can't work it out!我想要做的应该很简单,但我就是做不到!

I have a parent entity called Players and a child entity called PlayerTrainingEvents .我有一个名为Players的父实体和一个名为PlayerTrainingEvents 的子实体 (PlayerTrainingEvents is actually a join table, but I'm not involving more than these two tables in this example). (PlayerTrainingEvents 实际上是一个连接表,但在这个例子中我不涉及超过这两个表)。

I want to bring back all the Players (not just the ones with related PlayerTrainingEvents) AND their related PlayerTrainingEvents for a given TrainingEventID.我要带回所有的玩家(不只是那些与相关PlayerTrainingEvents)及其相关PlayerTrainingEvents对于给定TrainingEventID。

These are the (simplified) entities and their relationship:这些是(简化的)实体及其关系:

在此处输入图片说明

Here is some example data:以下是一些示例数据:

在此处输入图片说明

Using the above example data, if I want to show all the Players with their PlayerTrainingEvents for TrainingEventID 3, I should get the following results:使用上面的示例数据,如果我想显示所有玩家的 PlayerTrainingEvents 为 TrainingEventID 3,我应该得到以下结果:

在此处输入图片说明

In SQL, it's really easy:在 SQL 中,这真的很简单:

SELECT *
  FROM Players p
  left join PlayerTrainingEvents pte on p.ID = pte.PlayerID and pte.TrainingEventID = 3

In Linq, the nearest I can get is:在 Linq 中,我能得到的最近的是:

var results = await _context.Players
            .Include(p => p.PlayerTrainingEvents.Where(pte => pte.TrainingEventID == id)).ToListAsync();

...but the above code results in an error: "InvalidOperationException: Lambda expression used inside Include is not valid". ...但上述代码导致错误:“InvalidOperationException:Include 中使用的 Lambda 表达式无效”。

As you can probably tell, I'm still quite new to EF.正如您可能会说的那样,我对 EF 还是很陌生。 Having been able to anything I want easily in SQL, I'm struggling with how EF is supposed to make things easier!能够在 SQL 中轻松完成我想要的任何事情,我正在努力解决 EF 如何让事情变得更容易!

Any help would be gratefully appreciated.任何帮助将不胜感激。

Thanks for the answers/comments I received.感谢我收到的答案/评论。 I have managed to get the below query to work.我已经设法让下面的查询工作。 This queries the Players first and then performs an outer join with the PlayerTrainingEvents.这首先查询 Players,然后与 PlayerTrainingEvents 执行外部连接。

from p in Players
join pte in PlayerTrainingEvents on new { PlayerId = p.ID, TrainingEventID = 3 } 
                                 equals new { PlayerId = pte.PlayerID, TrainingEventID = pte.TrainingEventID } into ptes
from pte in ptes.DefaultIfEmpty()
select new  { p.ID, pte.TrainingEventID, pte.AttendanceCode }

That just seems a lot of code for what is a very simple SQL query however.然而,对于一个非常简单的 SQL 查询来说,这似乎有很多代码。 I still think SQL is easier but perhaps I just need to do some studying!我仍然认为 SQL 更容易,但也许我只需要做一些学习! If anyone has a better solution, I'd be really interested to see it.如果有人有更好的解决方案,我会非常有兴趣看到它。

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

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