Sqlite EF Core 5 不允许我进行不区分大小写的搜索

Joh*_*ape 1 sqlite entity-framework-core asp.net-core

因此,我尝试使用 ef-core 进行 linq 查询来执行 where 搜索,但无论我尝试什么,都无法让它执行不区分大小写的搜索。

例如,如果我搜索“星期二”,它不会获取任何数据,因为数据库中的所有内容都保存为“星期二”。

搜索后,我发现您必须通过 ef core 迁移告诉 sqlite 您希望它对每个属性不区分大小写,并使用以下代码。

b.Property<string>("DayOfWeek")
    .HasColumnType("TEXT COLLATE NOCASE");
Run Code Online (Sandbox Code Playgroud)

该信息位于 ContextModelSnapshot.cs 文件中。

所以我这样做了,删除了数据库并执行了“更新数据库”,创建了一个新数据库,但没有任何改变。

现在我当然可以.ToLower()在每个搜索中使用 the ,但是如果我忘记将其添加到每个 where 子句,那只会影响性能并增加失败的可能性。

我使用以下包来创建、迁移和访问数据库。

<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="5.0.1">
  <PrivateAssets>all</PrivateAssets>
  <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="5.0.1" />
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="5.0.1" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="5.0.1">
Run Code Online (Sandbox Code Playgroud)

我错过了什么或者我是否误解了 sqlite 不区分大小写查询的整个概念?

Vah*_*idN 5

不幸的是,提供的答案对我不起作用。以下是如何迭代stringEF-Core 的所有公开模型的所有属性并将其默认排序规则设置为nocase

public static void SetCaseInsensitiveSearchesForSQLite(this ModelBuilder modelBuilder)
{
    if (modelBuilder == null)
    {
        throw new ArgumentNullException(nameof(modelBuilder));
    }

    modelBuilder.UseCollation("NOCASE");

    foreach (var property in modelBuilder.Model.GetEntityTypes()
                                            .SelectMany(t => t.GetProperties())
                                            .Where(p => p.ClrType == typeof(string)))
    {
        property.SetCollation("NOCASE");
    }
}
Run Code Online (Sandbox Code Playgroud)

然后这样称呼它:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    if (modelBuilder == null)
    {
        throw new ArgumentNullException(nameof(modelBuilder));
    }

    modelBuilder.SetCaseInsensitiveSearchesForSQLite();
}
Run Code Online (Sandbox Code Playgroud)