我正在使用下面的代码在多列中搜索特定的字符串
IEnumerable<UserProductDetailResult> _query
= from eml in dc.UserProductDetails
join zk in dc.ZeekUsers on eml.aspnet_User.UserId equals zk.UserId
where eml.aspnet_User.LoweredUserName.Equals(strUserName.ToLower())
&& (eml.Username.Contains(strSearch)
|| eml.ProductURL.Contains(strSearch)
|| eml.Nickname.Contains(strSearch))
&& !eml.IsDeleted
&& eml.IsActive
select new UserProductDetailResult
{
_userProductDetail = eml,
_zeekUser = zk
};
其中 dc 是 DataContext 对象。
但这会返回 0 个结果。
从上面的代码生成的查询是
SELECT [t0].[UPID], [t0].[UserId], [t0].[PID], [t0].[Nickname], [t0].[Username], [t0].[ProductURL], [t0].[StartDt], [t0].[EndDt], [t0].[IsActive], [t0].[InfoData], [t0].[SocialNetworkingData], [t0].[AnalyticKey], [t0].[ProfileID], [t0].[UseDefaultAd], [t0].[UseDefaultEmail], [t0].[IsDeleted], [t0].[CreateDt], [t0].[LastUpdateDt], [t1].[ID], [t1].[UserId] AS [UserId2], [t1].[AccountType], [t1].[FirstName], [t1].[LastName], [t1].[Phone], [t1].[Address1], [t1].[Address2], [t1].[City], [t1].[State], [t1].[ZIP], [t1].[CountryID], [t1].[NickName1], [t1].[Nickname2], [t1].[AlternameEmail], [t1].[ProfileImage], [t1].[ZeekIdStatus], [t1].[RefZeekUserId], [t1].[IsActive] AS [IsActive2], [t1].[FailureCount], [t1].[IsBlocked], [t1].[IsFirstVisit], [t1].[IsWizardPassed], [t1].[IPAddress], [t1].[TimeZoneID], [t1].[CreateDt] AS [CreateDt2], [t1].[LastUpdateDt] AS [LastUpdateDt2]
FROM [dbo].[UserProductDetails] AS [t0]
INNER JOIN [dbo].[ZeekUsers] AS [t1] ON ((
SELECT [t2].[UserId]
FROM [dbo].[aspnet_Users] AS [t2]
WHERE [t2].[UserId] = [t0].[UserId]
)) = [t1].[UserId]
INNER JOIN [dbo].[aspnet_Users] AS [t3] ON [t3].[UserId] = [t0].[UserId]
WHERE ([t3].[LoweredUserName] = 'username') AND (([t0].[Username] LIKE 'a') OR ([t0].[ProductURL] LIKE 'a') OR ([t0].[Nickname] like 'a')) AND (NOT ([t0].[IsDeleted] = 1)) AND ([t0].[IsActive] = 1)
一旦删除下面的搜索行,它就会工作并返回,
&& (eml.Username.Contains(strSearch)
|| eml.ProductURL.Contains(strSearch)
|| eml.Nickname.Contains(strSearch))
但这不允许我搜索
谁能告诉我应该如何进行?
最佳答案
根据您生成的查询,我认为您正在使用 linq-to-sql
。你可以使用 SqlMethods.Like从 MSDN 生成正确的 like
查询运算符:
Determines whether a specific character string matches a specified pattern. This method is currently only supported in LINQ to SQL queries.
示例:
// first sample, any part of string
strSearch = string.Format("%[^a-zA-Z]{0}[^a-zA-Z]%", strSearch);
// on the end of the string
strSearch = string.Format("%[^a-zA-Z]{0}", strSearch);
//on the begining of the string
strSearch = string.Format("{0}[^a-zA-Z]%", strSearch);
在你的查询语句中..
(SqlMethods.Like(eml.Username, strSearch)
|| SqlMethods.Like(eml.ProductURL, strSearch)
|| SqlMethods.Like(eml.Nickname, strSearch))
否则,您可以在查询前的 strSearch
字符串中添加 %
字符,以生成包含字符串任何部分信息的查询,例如:
strSearch = string.Contat("%", strSearch, "%");
关于c# - 如何使用包含在 Linq to SQL 中搜索字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22389084/