linq 在where语句而不是子查询中过滤连接表

zbdgwd5y  于 2022-12-30  发布在  其他
关注(0)|答案(1)|浏览(131)

这是我使用EntityFramework for MySQL创建的数据库模型

  1. public class User
  2. {
  3. public Guid id { get; set; }
  4. public string? firstName { get; set; }
  5. public string? lastName { get; set; }
  6. public string? email { get; set; }
  7. public string? displayName { get; set; }
  8. public virtual List<UserRequest>? userRequests { get; set; }
  9. }
  1. public class UserRequest
  2. {
  3. public int id { get; set; }
  4. public string? action { get; set; }
  5. public string? domain { get; set; }
  6. public string? pathAccessing { get; set; }
  7. public string? applicationName { get; set; }
  8. public string? type { get; set; }
  9. public DateTime createdDate { get; set; }
  10. public Guid userId { get; set; }
  11. public User? user { get; set; }
  12. }

在这个模型中,一个用户可以有多个用户请求。所以我想查询用户是否访问过这个域。
在SQL语句中,这将是我的语句

  1. select * from User u
  2. inner join UserRequest ur on ur.userId = u.id
  3. where ur.domains in ("http://localhost", "http://localhost.dev")

这是我在linq中的声明

  1. var domainsList = new string[] {"http://localhost", "http://localhost.dev"};
  2. var result = _DBContext.User
  3. .Include(q=>
  4. q.userRequests
  5. ).Where((t)=> t.userRequests.any(u=>domainsList.Contains(u.domain)));

生成的SQL语句

  1. SELECT `u`.`id`, `u`.`displayName`, `u`.`email`, `u`.`firstName`, `u`.`lastName`, `u1`.`id`, `u1`.`action`, `u1`.`applicationName`, `u1`.`createdDate`, `u1`.`domain`, `u1`.`pathAccessing`, `u1`.`type`, `u1`.`userID`
  2. FROM `user` AS `u`
  3. LEFT JOIN `userRequest` AS `u1` ON `u`.`id` = `u1`.`userID`
  4. WHERE EXISTS (
  5. SELECT 1
  6. FROM `userRequest` AS `u0`
  7. WHERE (`u`.`id` = `u0`.`userID`) AND `u0`.`domain` IN ('http://localhost', 'http://localhost.dev'))
  8. ORDER BY `u`.`id`

生成的sql语句正在使用子查询而不是我期望的简单where表达式。我的数据库不大,所以在我的情况下,子查询比join + where表达式慢。
有没有一种方法可以重写我的linq语句,让dotnet生成类似于我所期望的SQL语句?或者这在Linq中是不可能的?
发现了一些类似的问题,但没有一个是试图达到我所希望的最终结果。
对不起,我英语不好

uubf1zoe

uubf1zoe1#

删除包含并使用联接。请遵循示例查询语法

  1. var query = from u in User
  2. join ur in UserRequest
  3. on u.ID equals ur.userID
  4. where (new string[] {'exampleofdomainList'}).Contains(ur.domain)
  5. select new { u, ur}

相关问题