2013-03-26 66 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