我正在尝试搜索数据库以查看字符串是否包含搜索词列表的元素。
var searchTerms = new List<string> { "car", "232" };
var result = context.Data.Where(data => data.Name.Contains(searchTerms) ||
data.Code.Contains(searchTerms));
如果searchTerms是一个字符串,但是我一直试图让它与字符串列表一起使用,这将有效。
基本上我需要SQL来说
SELECT * FROM Data
WHERE Name LIKE '%car%'
OR Name LIKE '%232%'
OR Code LIKE '%car%'
OR Code LIKE '%232%'
linq where list contains any in list似乎是我能找到的关闭事情。
Where(data => searchTerms.Contains(data.Name) || searchTerms.Contains(data.Code)
只会将完全匹配带回搜索字词列表。
我也尝试在Entity Framework中搜索多个关键字搜索,并且已经用尽了这些努力。有没有办法实现我的目标?
答案 0 :(得分:11)
I'm late to the party but using the SearchExtensions nuget package you could do something like the following
var result = context.Data.Search(x => x.Name, x => x.Code).Containing(searchTerms);
This builds an expression tree so will still perform the query on the server (and not in memory) and will essentially run the SQL you desire above
答案 1 :(得分:10)
您可以尝试使用Any
方法,我不确定它是否受支持,但值得尝试:
var result = context.Data.Where(data => searchTerms.Any(x => data.Name.Contains(x)) ||
searchTerms.Any(x => data.Code.Contains(x));
如果这为您提供NotSupportedException
,您可以在AsEnumerable
之前添加Where
来获取所有记录并在内存而不是数据库中执行查询。
答案 2 :(得分:1)
您可以使用Linq的Any函数查看数据中是否包含任何术语。
var result = context.Data.Where(data => searchTerms.Any(term => data.Name.Contains(term) ||
searchTerms.Any(term => data.Code.Contains(term));
答案 3 :(得分:0)
以下是一个完全的功能性示例,说明了如何使用多个关键字实施不同类型的搜索。
此示例特别针对@Hamza Khanzada的similar question ,涉及Pomelo.EntityFrameworkCore.MySql
。
它的作用类似于命名为@NinjaNye的库。
EqualsQuery()
使用了最简单的方法,该方法只是针对关键字的完全匹配来测试数据库字段(尽管大小写无关紧要)。这就是@Mohsen Esmailpour的建议。
它生成类似于以下内容的SQL:
SELECT `i`.`IceCreamId`, `i`.`Name`
FROM `IceCreams` AS `i`
WHERE LOWER(`i`.`Name`) IN ('cookie', 'berry')
ORDER BY `i`.`IceCreamId`
但是,这可能不足以满足您的情况,因为您不是在寻找完全匹配的 ,而是想返回仅包含 关键字(可能还有其他字词。)
AndContainsQuery()
使用了第二种方法,该方法仍然非常简单,但功能有所不同。它仅返回包含 all 关键字(可能还包含其他词)的结果。
它生成类似于以下内容的SQL:
set @__keyword_0 = 'Cookie';
set @__keyword_1 = 'choco';
SELECT `i`.`IceCreamId`, `i`.`Name`
FROM `IceCreams` AS `i`
WHERE
(LOCATE(LCASE(@__keyword_0), LCASE(`i`.`Name`)) > 0) AND
(LOCATE(LCASE(@__keyword_1), LCASE(`i`.`Name`)) > 0)
ORDER BY `i`.`IceCreamId`;
这不是您想要的,但我也很高兴展示它,因为它非常简单,无需手动构建表达式树即可完成
。最后,orContainsQuery()
使用了第三种方法,它可以手动构建表达式树的一部分。它构造多个嵌套WHERE
表达式的OR
表达式的主体。
这是您想要的 。
它生成类似于以下内容的SQL:
set @__keyword_0 = 'berry';
set @__keyword_1 = 'Cookie';
SELECT `i`.`IceCreamId`, `i`.`Name`
FROM `IceCreams` AS `i`
WHERE
(LOCATE(LCASE(@__keyword_0), LCASE(`i`.`Name`)) > 0) OR
(LOCATE(LCASE(@__keyword_1), LCASE(`i`.`Name`)) > 0)
ORDER BY `i`.`IceCreamId`;
这是功能齐全的控制台项目:
using System;
using System.Diagnostics;
using System.Linq;
using System.Linq.Expressions;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using Pomelo.EntityFrameworkCore.MySql.Storage;
namespace IssueConsoleTemplate
{
public class IceCream
{
public int IceCreamId { get; set; }
public string Name { get; set; }
}
public class Context : DbContext
{
public DbSet<IceCream> IceCreams { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder
.UseMySql(
"server=127.0.0.1;port=3306;user=root;password=;database=so60914868",
b => b.ServerVersion(new ServerVersion("8.0.20-mysql")))
.UseLoggerFactory(
LoggerFactory.Create(
b => b
.AddConsole()
.AddFilter(level => level >= LogLevel.Information)))
.EnableSensitiveDataLogging()
.EnableDetailedErrors();
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<IceCream>(
entity =>
{
entity.HasData(
new IceCream {IceCreamId = 1, Name = "Vanilla"},
new IceCream {IceCreamId = 2, Name = "Berry"},
new IceCream {IceCreamId = 3, Name = "Strawberry"},
new IceCream {IceCreamId = 4, Name = "Berry & Fruit"},
new IceCream {IceCreamId = 5, Name = "cookie"},
new IceCream {IceCreamId = 6, Name = "Chocolate chip cookie"},
new IceCream {IceCreamId = 7, Name = "Choco-Cookie & Dough"});
});
}
}
internal class Program
{
private static void Main()
{
using (var context = new Context())
{
context.Database.EnsureDeleted();
context.Database.EnsureCreated();
}
EqualsQuery();
AndContainsQuery();
OrContainsQuery();
}
private static void EqualsQuery()
{
//
// This will find only matches that match the word exactly (though case-insensitive):
//
using var context = new Context();
var keywords = new[] {"Cookie", "berry"}
.Select(s => s.ToLower())
.ToArray();
var equalsResult = context.IceCreams
.Where(i => keywords.Contains(i.Name.ToLower()))
.OrderBy(i => i.IceCreamId)
.ToList();
Debug.Assert(equalsResult.Count == 2);
Debug.Assert(
equalsResult[0]
.Name == "Berry");
Debug.Assert(
equalsResult[1]
.Name == "cookie");
}
private static void AndContainsQuery()
{
//
// This will find matches, that contain ALL keywords (and other words, case-insensitive):
//
using var context = new Context();
var keywords = new[] {"Cookie", "choco"};
var andContainsQuery = context.IceCreams.AsQueryable();
foreach (var keyword in keywords)
{
andContainsQuery = andContainsQuery.Where(i => i.Name.Contains(keyword, StringComparison.CurrentCultureIgnoreCase));
}
var andContainsResult = andContainsQuery
.OrderBy(i => i.IceCreamId)
.ToList();
Debug.Assert(andContainsResult.Count == 2);
Debug.Assert(
andContainsResult[0]
.Name == "Chocolate chip cookie");
Debug.Assert(
andContainsResult[1]
.Name == "Choco-Cookie & Dough");
}
private static void OrContainsQuery()
{
//
// This will find matches, that contains at least one keyword (and other words, case-insensitive):
//
using var context = new Context();
var keywords = new[] {"Cookie", "berry"};
// The lambda parameter.
var iceCreamParameter = Expression.Parameter(typeof(IceCream), "i");
// Build the individual conditions to check against.
var orConditions = keywords
.Select(keyword => (Expression<Func<IceCream, bool>>) (i => i.Name.Contains(keyword, StringComparison.OrdinalIgnoreCase)))
.Select(lambda => (Expression) Expression.Invoke(lambda, iceCreamParameter))
.ToList();
// Combine the individual conditions to an expression tree of nested ORs.
var orExpressionTree = orConditions
.Skip(1)
.Aggregate(
orConditions.First(),
(current, expression) => Expression.OrElse(expression, current));
// Build the final predicate (a lambda expression), so we can use it inside of `.Where()`.
var predicateExpression = (Expression<Func<IceCream, bool>>)Expression.Lambda(
orExpressionTree,
iceCreamParameter);
// Compose and execute the query.
var orContainsResult = context.IceCreams
.Where(predicateExpression)
.OrderBy(i => i.IceCreamId)
.ToList();
Debug.Assert(orContainsResult.Count == 6);
Debug.Assert(orContainsResult[0].Name == "Berry");
Debug.Assert(orContainsResult[1].Name == "Strawberry");
Debug.Assert(orContainsResult[2].Name == "Berry & Fruit");
Debug.Assert(orContainsResult[3].Name == "cookie");
Debug.Assert(orContainsResult[4].Name == "Chocolate chip cookie");
Debug.Assert(orContainsResult[5].Name == "Choco-Cookie & Dough");
}
}
}