问题
Is there an equivalent of IsNumeric in EF Core or by using linq or Dynamic Sql or similar?
I am trying to get only the rows with numeric values from a nvarchar column.
回答1:
You could use Raw SQL Queries
Security Note: Always use parameterization for raw SQL queries
Given this dataset/result:
The entity class for EF Core: Sandbox.cs
public class Sandbox
{
public int SandboxId { get; set; }
public string StringOrNumber { get; set; }
}
Create a DbSet in your context:
public DbSet<Sandbox> Sandboxes { get; set; }
Mark as no key:
modelBuilder.Entity<Sandbox>().HasNoKey();
Test:
public async Task<IList<Sandbox>> GetNumberList()
{
// 1 = number, 0 = string
var isNumeric = new SqlParameter("isNumeric", 1);
var listOfNumbers = await _context.Sandboxes
.FromSqlRaw("SELECT SandboxId, StringOrNumber FROM dbo.Sandbox WHERE ISNUMERIC(StringOrNumber) = @isNumeric", isNumeric)
.ToListAsync();
return listOfNumbers;
}
An alternative to FromSqlRaw is FromSqlInterpolated.
var listOfNumbers = await _context.Sandboxes
.FromSqlInterpolated($"SELECT SandboxId, StringOrNumber FROM dbo.Sandbox WHERE ISNUMERIC(StringOrNumber) = {isNumeric}")
.ToListAsync();
来源:https://stackoverflow.com/questions/60926152/isnumeric-in-ef-core