Define the function(s) you want to call:
public static class SqlFunctions
{
public static string Format(decimal? value, string format) => value?.ToString(format) ?? string.Empty;
public static void Register(ModelBuilder modelBuilder)
{
var method = typeof(SqlFunctions).GetMethod(nameof(Format));
modelBuilder.HasDbFunction(method).HasTranslation(TranslateFormat);
}
private static SqlExpression TranslateFormat(IReadOnlyCollection<SqlExpression> args)
{
return SqlFunctionExpression.Create("FORMAT", args, typeof(string), null);
}
}
Register the function(s) in your
DbContext
:
public class YourContext : DbContext
{
...
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
SqlFunctions.Register(modelBuilder);
...
}
...
}
Call the function(s) in your query:
var query = from obj in yourContext.YourTable
where SqlFunctions.Format(obj.Number, "0.00").Contains("03.1")
select obj;
NB: You don't need the
CAST
;
FORMAT
already returns an
nvarchar
.
NB 2: If you need the full abilities of the
LIKE
function, use
EF.Functions.Like
:
where EF.Functions.Like(SqlFunctions.Format(obj.Number, "0.00"), "%3.[1-5]%")
But for the simple comparison shown in your question,
Contains
is sufficient.