如何编写 Entity Framework 查询才能加入 ICollection?

How to write Entity Framework query to be able to join to the ICollection?

我正在尝试为给定的 Profile.email.[=23= 计算 return User.NameUser.Email 的 Entity Framework 语法]

1 个个人资料可以有 N 个类别。 1 个类别可以有 1 个用户。

在SQL中我会写:

SELECT U.NAME, U.EMAIL
FROM PROFILE P
JOIN CATEGORY C ON P.ID = C.PROFILEID
JOIN USER U ON C.USERID = U.ID
WHERE P.EMAIL = 'SOME@EMAIL.COM'

这是我尝试过的:

var data = await _context.Profiles
                         .AsNoTracking()
                         .Where(p => p.Categories.Users.email == 'some@email.com')
                         .Select(u => new 
                                      {
                                          UName = u.Name,
                                          UEmail = u.Email
                                      }).ToListAsync();

问题是 p.Categories 是一个 ICollection,所以我不知道如何继续,因为 p.Categories 不允许我访问 .Users .我可以写 p.Categories.Where.... 但我不确定如何继续。

我应该从 _context.Users. 开始,而不是从 _context.Profiles. 开始吗?

有人可以帮助我在编写 Entity Framework 查询时如何考虑该方法吗?

因此,只需开始以 LINQ 形式查询类别即可:

from c in _context.Categories
where c.Profile.Email == someEmail
select new { c.User.Name, c.User.Email }

或 Lambda 形式:

   _context.Categories
           .Where( c => c.Profile.Email == someEmail )
           .Select( c => new {c.User.Name, c.User.Email}

或从 Profiles 开始并使用 SelectMany,其 LINQ 形式类似于

from p in _context.Profiles
from c in p.Categories
where p.Email == someEmail
select new {c.User.Name, c.User.Email}

或 Lambda 形式:

_context.Profiles
        .Where(p => p.Email == someEmail)
        .SelectMany(p => p.Categories)
        .Select( c => new {c.User.Name, c.User.Email} )

如果我对你的模型的理解正确,这应该有效:

var data = await _context.Categories.AsNoTracking()
                     .Where(c=>c.Profile.email == "some@email.com")
                     .Select(c=>new {
                         UName=c.User.Name,
                         UEmail=c.User.Email
                     }).ToListAsync();

当然这需要您的模型设置导航属性。