2013-03-26 67 views
0

你好请你能告诉我在最好的方式来实现LINQ过滤多个列VB.net 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

感谢保罗

回答

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() 
+0

得益于它的工作就像一个梦要对数据库执行 – Easty 2013-03-26 14:16:54