这是我使用EntityFramework for MySQL创建的数据库模型
public class User
{
public Guid id { get; set; }
public string? firstName { get; set; }
public string? lastName { get; set; }
public string? email { get; set; }
public string? displayName { get; set; }
public virtual List<UserRequest>? userRequests { get; set; }
}
public class UserRequest
{
public int id { get; set; }
public string? action { get; set; }
public string? domain { get; set; }
public string? pathAccessing { get; set; }
public string? applicationName { get; set; }
public string? type { get; set; }
public DateTime createdDate { get; set; }
public Guid userId { get; set; }
public User? user { get; set; }
}
在这个模型中,一个用户可以有多个用户请求。所以我想查询用户是否访问过这个域。
在SQL语句中,这将是我的语句
select * from User u
inner join UserRequest ur on ur.userId = u.id
where ur.domains in ("http://localhost", "http://localhost.dev")
这是我在linq中的声明
var domainsList = new string[] {"http://localhost", "http://localhost.dev"};
var result = _DBContext.User
.Include(q=>
q.userRequests
).Where((t)=> t.userRequests.any(u=>domainsList.Contains(u.domain)));
生成的SQL语句
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`
FROM `user` AS `u`
LEFT JOIN `userRequest` AS `u1` ON `u`.`id` = `u1`.`userID`
WHERE EXISTS (
SELECT 1
FROM `userRequest` AS `u0`
WHERE (`u`.`id` = `u0`.`userID`) AND `u0`.`domain` IN ('http://localhost', 'http://localhost.dev'))
ORDER BY `u`.`id`
生成的sql语句正在使用子查询而不是我期望的简单where表达式。我的数据库不大,所以在我的情况下,子查询比join + where表达式慢。
有没有一种方法可以重写我的linq语句,让dotnet生成类似于我所期望的SQL语句?或者这在Linq中是不可能的?
发现了一些类似的问题,但没有一个是试图达到我所希望的最终结果。
对不起,我英语不好
1条答案
按热度按时间uubf1zoe1#
删除包含并使用联接。请遵循示例查询语法