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

Usersテーブルがマップされた LINQ to SQL DBContext が既に準備されていると仮定します。

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 に答える