我有以下要转换为EF Linq查询的SQL查询,但我不知道该如何编写“ like”部分。
SELECT DepartmentsWithChildren.*
FROM dbo.People
INNER JOIN dbo.DepartmentPersons
ON DepartmentPersons.Person_Id = People.Id
INNER JOIN dbo.DepartmentsWithChildren
ON DepartmentsWithChildren.lvl LIKE '%,' + CAST(DepartmentPersons.Department_Id AS VARCHAR(50)) + ',%'
WHERE UserId = '01cb89b4-9f81-4012-a4d9-5a38468a7433'
上述查询的示例结果
Id ParentDepartmentId lvl
58 27 ,27,3,1,
64 27 ,27,3,1,
67 27 ,27,3,1,
77 27 ,27,3,1,
90 27 ,27,3,1,
93 27 ,27,3,1,
100 27 ,27,3,1,
102 27 ,27,3,1,
106 27 ,27,3,1,
134 27 ,27,3,1,
137 27 ,27,3,1,
396 27 ,27,3,1,
414 27 ,27,3,1,
171 67 ,67,27,3,1,
206 67 ,67,27,3,1,
219 67 ,67,27,3,1,
为澄清起见,我想知道如何做一个JOIN的LIKE部分,我知道在WHERE子句中可以使用contains,但是对于JOINS,我发现的每个示例都仅使用等于f.eks: How to join tables in EF LINQ
答案 0 :(得分:2)
您只能在Linq中使用join时使用equals运算符,以下是一种可能的解决方法。
假设您的DbContext
被称为db:
var result = from people in db.People
from departmentWithChildren in db.DepartmentsWithChildren
join departmentPerson in db.DepartmentPersons
on people.Id equals departmentPerson.Person_Id
where departmentWithChildren.Any(d => d.lvl.Contains("," +
departmentPerson.Deparment_Id + ",")) &&
people.UserId = "01cb89b4-9f81-4012-a4d9-5a38468a7433"
select departmentWithChildren;
答案 1 :(得分:1)
一种简便的方法是使用两个linq查询。
var dict = from row in entities.departments where yada yada select row.Id;
var query = from row in entities.departmentpersons where
dict.Contains(row.departmentId)
select row;