Home > Back-end >  How to write this extension method to be translatable by EF Core to SQL Server?
How to write this extension method to be translatable by EF Core to SQL Server?

Time:10-03

I have this extension method in my .NET code check if a string is something:

public static bool IsSomething(this string text)
{
   var isNothing = string.IsNullOrEmpty(text) || string.IsNullOrWhiteSpace(text);
   return !isNothing;
}

However, I can't use it in my EF Core quereis:

dbset.Where(i => i.Title.IsSomething()); // throws non-translatable error

I know that I can rewrite my query as:

dbset.Where(i => i.Title != null && i.Title.Trim() != ""); // this works, but it's too verbose

But I really don't want to write that long non-descriptive code.

How can I have IsSomething to be translatable for SQL Server?

CodePudding user response:

Just use IsNullOrWhiteSpace; it does what IsNullOrEmpty does:

Return true if the value parameter is null or Empty, or if value consists exclusively of white-space characters. -- documentation for IsNullOrWhiteSpace

And it is mapped by EF Core to an SQL of

@value IS NULL OR LTRIM(RTRIM(@value)) = N''

This means your IsSonething method is effectively !IsNullOrWhiteSpace, which EF will translate if you use

CodePudding user response:

You cannot translate this method to SQL Server. However, you can use a method that returns Expression. For example:

public static Expression<Func<Student, bool>> IsSomething()
{
    return (s) => string.IsNullOrEmpty(s.FirstName) || string.IsNullOrWhiteSpace(s.FirstName);
}

Usually, you should call AsEnumerable before using methods:

dbset.AsEnumerable().Where(i => i.Title.IsSomething());

But it will load all entities from data base.

  • Related