在Entity Framework Core 2.0中增加一个很酷的功能:EF.Functions.Like()
,最终解析为SQL中的Like
语句,以便于在 LINQ 查询中直接调用。
不过Entity Framework 中默认提供了StartsWith
、Contains
和EndsWith
方法用于解决模糊查询,那么为什么还要提供EF.Functions.Like
,今天我们来重点说说它们之间的区别。
表结构定义
在具体内容开始之前,我们先简单说明一下要使用的表结构。
public class Category
{
public int CategoryID { get; set; }
public string CategoryName { get; set; }
public override string ToString()
{
return $"{
nameof(CategoryID)}: {CategoryID}, {
nameof(CategoryName)}: {CategoryName}";
}
}
在 Category 类型定义了两个字段:CategoryID、CategoryName。
public class SampleDbContext : DbContext
{
public virtual DbSet Categories { get; set; }protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer("数据库连接字符串");base.OnConfiguring(optionsBuilder);
}protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
EntityTypeBuilder entityTypeBuilder = modelBuilder.Entity();
entityTypeBuilder.ToTable("Category");
entityTypeBuilder.HasKey(e => e.CategoryID);
entityTypeBuilder.Property(e => e.CategoryID).UseSqlServerIdentityColumn();
}
}
我们使用 SampleDbContext 来访问数据库。
CategoryID | CategoryName |
---|---|
1 | Clothing |
2 | Footwear |
3 | Accessories |
在数据库的 Category 表中插入上面三行记录。
EF.Functions.Like 使用示例
我们来看一个EF.Functions.Like()
查询示例,查询 CategoryName 字段中包括字符串 “t” 的数据,传递的参数是 “%t%”:
[Fact]
public void Like()
{
using (var dataContext = new SampleDbContext()) {
var result= dataContext.Categories.Where(item => EF.Functions.Like(item.CategoryName, "%t%")).ToList();
foreach (var item in result) {