Using Dynamic LINQ with EF.Functions.Like

703 Views Asked by At

On the Dynamic LINQ website there's an example using the Like function.

I am unable to get it to work with ef core 3.1

[Test]
public void DynamicQuery()
{
    using var context = new SamDBContext(Builder.Options);
    var config = new ParsingConfig { ResolveTypesBySimpleName = true };
    var lst = context.Contacts.Where(config, "DynamicFunctions.Like(FirstName, \"%Ann%\")".ToList();
    lst.Should().HaveCountGreaterThan(1);
}

Example from the Dynamic LINQ website

var example1 = Cars.Where(c => EF.Functions.Like(c.Brand, "%t%"));
example1.Dump();

var config = new ParsingConfig { ResolveTypesBySimpleName = true };
var example2 = Cars.Where(config, "DynamicFunctions.Like(Brand, \"%t%\")");
example2.Dump();

Looks like my code. But I am getting the following error

System.Linq.Dynamic.Core.Exceptions.ParseException : No property or field 'DynamicFunctions' exists in type 'Contact'
1

There are 1 best solutions below

0
On

you don't need the ResolveTypesBySimpleName, implement your wont type provider.

The piece below people to use PostgreSQL ILike with unnaccent

public class LinqCustomProvider : DefaultDynamicLinqCustomTypeProvider
{
    public override HashSet<Type> GetCustomTypes()
    {
        var result = base.GetCustomTypes();

        result.Add(typeof(NpgsqlFullTextSearchDbFunctionsExtensions));
        result.Add(typeof(NpgsqlDbFunctionsExtensions));
        result.Add(typeof(DbFunctionsExtensions));
        result.Add(typeof(DbFunctions));
        result.Add(typeof(EF));
        return result;
    }
}


// ....

var expressionString = $"EF.Functions.ILike(EF.Functions.Unaccent(People.Name), \"%{value}%\")";
var config = new ParsingConfig()
{
   DateTimeIsParsedAsUTC = true,
   CustomTypeProvider = new LinqCustomProvider()
};
return query.Where(config, expressionString);

Hope this helps people, took me some time to get this sorted.