我是linq的新手。我正在尝试编写一个linq查询,它将搜索数据库中的3个字段。但是,如果任何字段为空或无,则它不会在查询中包含该字段。
搜索对象
Public Class Search
Public Property firstName As String
Public Property surname As String
Public Property address As String
End Class
表
CREATE TABLE [dbo].[user] (
[id] [int] IDENTITY(1,1) NOT NULL,
[firstName] [nvarchar](50) NULL,
[surname] [nvarchar](50) NULL,
[fullAddress] [nvarchar](1050) NULL
我的尝试,但这不会得到任何数据
(From it In db.user
Where (
searchItems.firstName IsNot Nothing
AndAlso it.firstName.Contains(searchItems.firstName))
AndAlso (searchItems.surname IsNot Nothing
AndAlso it.surname.Contains(searchItems.surname))
AndAlso (searchItems.address IsNot Nothing
AndAlso it.fullAddress.Contains(searchItems.address))
Select it).
ToList
此外,我需要将此限制为250条记录
提前致谢 保罗
答案 0 :(得分:0)
每个字符串检查还应检查该值是否为空字符串(“”)。如果您为每个字符串检查添加额外的检查,您应该能够完成此操作,例如:
(From it In db.user
Where (Not String.IsNullOrEmpty(searchItems.firstName)) Or (it.firstName.Contains(searchItems.firstName))
AndAlso (Not String.IsNullOrEmpty(searchItems.surname) Or (it.surname.Contains(searchItems.surname))
AndAlso (Not String.IsNullOrEmpty(searchItems.address) Or (it.fullAddress.Contains(searchItems.address))
Select it).Take(250).ToList