Use array of ints parameter in FromSQL query and Where In clause

Miguel Moura :

I have a list of ints:

var ids = new List { 10, 20 };

And I need to find Users with that ids:

context.Users.FromSqlInterpolated($@" 
  select Users.* 
  where Users.Id in ({String.Join(',', ids)})"

But I get the following error:

'Conversion failed when converting the nvarchar value '10, 20' to data type int.'

How can I use such a parameter?

Ivan Stoev :

Using Interpolated method is not appropriate here, because {String.Join(',', ids)} defines single string placeholder, hence EF Core binds single nvarchar parameter with value '10,20', so the actual SQL is like this

select Users.* 
where Users.Id in ('10,20')

which is invalid, hence the exception.

You should use Raw method instead. Either

var query = context.Users.FromSqlRaw($@" 
select Users.* 
where Users.Id in ({String.Join(',', ids)})");

which will embed literal values

select Users.* 
where Users.Id in (10,20)

or if you want to parameterize it, generate parameter placeholders like {0}, {1} etc. inside the SQL and pass values separately:

var placeholders = string.Join(",", Enumerable.Range(0, ids.Count)
    .Select(i => "{" + i + "}"));
var values = ids.Cast<object>().ToArray();

var query = context.Users.FromSqlRaw($@" 
select Users.* 
where Users.Id in ({placeholders})", values);

which would generate SQL like this

select Users.* 
where Users.Id in (@p0,@p1)

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=367765&siteId=1