将 SQL 插入到 LINQ 查询中

Interpolated SQL to LINQ-query

以下 SQL 查询如何转换为 LINQ:

SELECT TOP 2 A.* FROM UserInterests AS UIa
INNER JOIN UserInterests AS UIb ON UIb.InterestId = UIa.InterestId
INNER JOIN AspNetUsers AS A ON A.Id = UIb.ApplicationUserId
WHERE UIa.ApplicationUserId = {userId}
AND NOT UIb.ApplicationUserId = {userId}
AND (
    A.Location LIKE {locationSubString + "%"} OR
    A.Location LIKE {neighbours[0] + "%"} OR
    A.Location LIKE {neighbours[1] + "%"} OR
    A.Location LIKE {neighbours[2] + "%"} OR
    A.Location LIKE {neighbours[3] + "%"} OR
    A.Location LIKE {neighbours[4] + "%"} OR
    A.Location LIKE {neighbours[5] + "%"} OR
    A.Location LIKE {neighbours[6] + "%"} OR
    A.Location LIKE {neighbours[7] + "%"}
)
ORDER BY NEWID()

我随机选择了两个离我很近并且有相同兴趣的用户。上面的查询是用 DbSet.FromSqlInterpolated 执行的。 userId 变量是我的 id,locationSubString + neighbors-array 是 geohashes。

我有以下这些,但我不确定如何匹配兴趣:

dbContext.Users.Where(u => (
    u.Location.StartsWith(locationSubString) ||
    u.Location.StartsWith(neighbours[0]) ||
    u.Location.StartsWith(neighbours[1]) ||
    u.Location.StartsWith(neighbours[2]) ||
    u.Location.StartsWith(neighbours[3]) ||
    u.Location.StartsWith(neighbours[4]) ||
    u.Location.StartsWith(neighbours[5]) ||
    u.Location.StartsWith(neighbours[6]) ||
    u.Location.StartsWith(neighbours[7])
) && u.Id != userId
).Include(u => u.Interests)

这可以在一次查询中完成吗?或者我需要先查询自己的兴趣,然后将其与该列表进行比较(myInterests 是一个列表):

...
.Include(u => u.Interests)
.Where(u => u.Interests.Any(i => myInterests.Contains(i)))

这是我想出的匹配代码:

var currentPersonId = 1;
var data = context.UserInterests
  .Join(context.UserInterests, x => x.InterestID, x => x.InterestID, (a, b) => new { CurrentInterest = a, MatchedInterest = b })
  .Where(x => x.CurrentInterest.UserID == currentPersonId && x.MatchedInterest.UserID != currentPersonId)
  .Select(x => x.MatchedInterest.User)
  .Distinct()
  .Where(x => x.Location.StartsWith("a"))
  .OrderBy(u => Guid.NewGuid())
  .Take(2)
  .ToArray();

您可以看到它适用于示例数据 here