Home > Back-end >  Pass a String as Parameter Into _context.Database.SqlQuery ASP.NET MVC 5
Pass a String as Parameter Into _context.Database.SqlQuery ASP.NET MVC 5

Time:12-10

I have A controller

  public ActionResult Index(int[] eo){ employes = _context.Database.SqlQuery(select * from table where tableId IN (@p0),String.Join(",", eo))}

The problem is the data of @p0 is being passed as string and TableID is int. The debug shows @p0 as ('10,2,3,5') what I want is (10,2,3,5).

How I can handle this problem?

CodePudding user response:

There are probably more elegant ways to solve this problem, but you can just split the string into a list of strings and parse each of them to int.

Something like this:

string test = "10,2,3,5";
List<string> stringList = test.Split(",").ToList();
List<int> intList = new List<int>();
foreach(string str in stringList)
{
    intList.Add(int.Parse(str));
}

CodePudding user response:

For SQL Server you can use JSON:

public ActionResult Index(int[] eo)
{ 
  var sql = @"
  select * 
  from table 
  where tableId IN (select value from openjson(@p0))
  ";

  var json = "["   String.Join(",", eo)   "]";

  var employes = _context.Database.SqlQuery(sql,json).ToList();
}
  • Related