嗨,请您告诉我在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中执行此操作
谢谢保罗
答案 0 :(得分: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()