Sending parameters to EF Core SqlQuery

36 views Asked by At

Is sending parameters like this with SqlQuery safe against SQL injection?

var page_param = new SqlParameter("page_param", page);
var pageSize_param = new SqlParameter("pageSize_param", pageSize);

var users = _context!.Database.SqlQuery<UserDTO>($"SELECT u.Id,u.FirstName,u.LastName,u.JoinDate,u.UserName,u.Email,u.EmailConfirmed,u.PhoneNumber,r.Name as Role FROM Users as u inner join UserRoles as ur on u.Id = ur.UserId inner join Roles r on ur.RoleId = r.Id order by u.JoinDate OFFSET {page_param} ROWS FETCH NEXT {pageSize_param} ROWS ONLY ");

I want to write secure SQL query

1

There are 1 answers

2
Svyatoslav Danyliv On

From documentation of SqlQuery-Remarks

Any parameter values you supply will automatically be converted to a DbParameter.

So, yes it is safe. And you can pass just integers ans strings without using SqlParameter.

Note that, for such simple queries better to use LINQ.