简体   繁体   中英

String.Compare in async method and EntityFramework Core

I tried these :

public async Task<bool> NameExists(string name)
{
    var productCategories = await this._dbContext.ProductCategories
        .Where(c => String.Compare(c.Name, name, StringComparison.InvariantCultureIgnoreCase) > 0).ToListAsync();

    return productCategories.Count > 0;
}

public async Task<bool> NameExists(string name)
{
    int count = await this._dbContext.ProductCategories
        .CountAsync(c => String.Compare(c.Name, name, StringComparison.InvariantCultureIgnoreCase) > 0).t

    return count != 0;
}

but in both cases I get this error message :

System.InvalidOperationException: 'The LINQ expression 'DbSet<ProductCategory>()
    .Where(p => string.Compare(
        strA: p.Name, 
        strB: __name_0, 
        comparisonType: InvariantCultureIgnoreCase) > 0)' could not be translated

I searched around the web but don't find any solution.

As temp "solution" I use this :

public async Task<bool> NameExists(string name)
{
    return await this._dbContext.ProductCategories.AnyAsync(x => x.Name.Trim().ToLower() == name.Trim().ToLower());

Do you have an idea how solve this ?

Thanks, }

You can force a case-insensitive collation, see the documentation for more details

public async Task<bool> NameExists(string name)
{
    var productCategories = await this._dbContext.ProductCategories
        .Where(c => EF.Functions.Collate(c.Name, "Latin1_General_CI_AS") == name)
        .ToListAsync();

    return productCategories.Count > 0;
}

Setting the collation on that column to be case-insensitive would mean you don't need any of this. The comparison would automatically be case-insensitive, and could use an index.


This particular query is in any case inefficient. You only want to know about existence, so use .Any instead of .Count

public async Task<bool> NameExists(string name)
{
    var exists = await this._dbContext.ProductCategories
        .Where(c => EF.Functions.Collate(c.Name, "Latin1_General_CI_AS") == name)
        .Any();

    return exists;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM