以下是一个功能齐全的示例,说明如何使用多个关键字实现不同类型的搜索。
这个例子特别针对@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`
但是,这对于您的情况可能还不够,因为您不是在寻找 exact 匹配项,而是希望返回具有仅 包含 关键字的字段的行 (可能还有其他词)。
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()使用了第三种方法,手动构建了部分表达式树。它构造了多个嵌套OR 表达式的WHERE 表达式的主体。
这是你想要的。
它生成类似于以下的 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");
}
}
}