0

嗨,你能告诉我在 LINQ 中实现多列过滤的最佳方法吗

桌子:

CREATE TABLE [dbo].[user] (
[id] [int] IDENTITY(1,1) NOT NULL,
[firstName] [nvarchar](50) NULL,
[surname] [nvarchar](50) NULL,
[fullAddress] [nvarchar](1050) NULL

我通常会为此使用 SQL

Dim firstname as string = 'bob'
Dim surname as String = 'holdness'
Dim address as String = 'blockbuster street'
Dim Stmquery as string = 'Select * from users '
if not String.isnullorEmpty(firstname) or not String.isnullorEmpty(surname) or not String.isnullorEmpty(address) then 
Stmquery = Stmquery & "where"
end if
if not String.isnullorEmpty(firstname) then
Stmquery = Stmquery & " firstname = " & firstname
end if
    if not String.isnullorEmpty(surname) then
Stmquery = Stmquery & " surname = " & surname
end if
    if not String.isnullorEmpty(address) then
Stmquery = Stmquery & " address = " & address
end if

所以基本上如果字符串为空,它将显示该列的所有记录

有人可以告诉我如何在 LINQ 中执行此操作

谢谢保罗

4

1 回答 1

1

我假设您已经准备好 LINQ to SQL DBContext 并Users映射了表。

您可以轻松地扩展您的查询,因为它不会在您调用ToList(), ToArray(), First(),Last()等之前对数据库执行。

Dim query = dbContext.Users;

If Not String.IsNullOrEmpty(firstname) Then
    query = query.Where(Function(u) u.FirstName = firstname)
End If

If Not String.IsNullOrEmpty(surname) Then
    query = query.Where(Function(u) u.Surname = surname)
End If

If Not String.IsNullOrEmpty(address) Then
    query = query.Where(Function(u) u.Address = address)
End If

' query execution is here, after next line '
Dim results = query.ToList()
于 2013-03-26T10:15:07.263 回答