EF Core中的IsNumeric [英] IsNumeric in EF Core
本文介绍了EF Core中的IsNumeric的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在EF Core中或通过使用linq或Dynamic Sql或类似方法是否存在IsNumeric的等效项?
我试图从nvarchar列中仅获取具有数字值的行。
解决方案
您可以使用
EF核心的实体类:Sandbox.cs
公共类Sandbox
{
public int SandboxId {get;组; }
公共字符串StringOrNumber {get;组; }
}
在您的上下文中创建DbSet:
public DbSet< Sandbox>沙盒{get;组; }
标记为无键:
modelBuilder.Entity&Sandbox>()。HasNoKey();
测试:
公共异步任务< IList< Sandbox>> GetNumberList()
{
// 1 =数字,0 =字符串
var isNumeric = new SqlParameter( isNumeric,1);
var listOfNumbers =等待_context.Sandboxes
.FromSqlRaw( SELECT SandboxId,StringOrNumber FROM dbo.Sandbox WHERE ISNUMERIC(StringOrNumber)= @isNumeric,isNumeric)
.ToListAsync( );
返回listOfNumbers;
}
FromSqlRaw的替代方法是
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.
解决方案
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();
这篇关于EF Core中的IsNumeric的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文