IsNumeric in EF Core

拟墨画扇 提交于 2020-06-28 06:46:29

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!