For LINQ to SQL queries with Entity Framework Core, ISNUMERIC
function is part of EF Core 6.0 under EF.Functions
Before version 6.0, you can create a user-defined function mapping !
User-defined function mapping
: Apart from mappings provided by EF Core providers, users can also define custom mapping. A user-defined mapping extends the query translation according to the user needs. This functionality is useful when there are user-defined functions in the database, which the user wants to invoke from their LINQ query for example.
await using var ctx = new BlogContext();
await ctx.Database.EnsureDeletedAsync();
await ctx.Database.EnsureCreatedAsync();
_ = await ctx.Blogs.Where(b => ctx.IsNumeric(b.Name)).ToListAsync();
public class BlogContext : DbContext
{
public DbSet<Blog> Blogs { get; set; }
static ILoggerFactory ContextLoggerFactory
=> LoggerFactory.Create(b => b.AddConsole().AddFilter("", LogLevel.Information));
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
=> optionsBuilder
.UseSqlServer(@"Server=localhost;Database=test;User=SA;Password=Abcd5678;Connect Timeout=60;ConnectRetryCount=0")
.EnableSensitiveDataLogging()
.UseLoggerFactory(ContextLoggerFactory);
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.HasDbFunction(IsNumericMethodInfo)
.HasName("ISNUMERIC")
.IsBuiltIn();
}
private static readonly MethodInfo IsNumericMethodInfo = typeof(BlogContext)
.GetRuntimeMethod(nameof(IsNumeric), new[] { typeof(string) });
public bool IsNumeric(string s) => throw new NotSupportedException();
}
public class Blog
{
public int Id { get; set; }
public string Name { get; set; }
}