public List<PostJobListModel> GetPostsByCompanyId(int id, int s, int d, int p)
{
string command = @"select Id,Title,Cities = STUFF(
(SELECT ',' + City.Name
FROM City where City.Id in (select Id from LocaitonJobRelationship as ljr where ljr.JobId = PostJob.Id)
FOR XML PATH ('')), 1, 1, ''),
Features = STUFF(
(SELECT ',' + Feature.Name
FROM Feature where Feature.Id in (select FeatureId from FeatureJobRelationship as fjr where fjr.JobId = PostJob.Id and (fjr.CategoryId in (@s,@d,@p) ) )FOR XML PATH('')), 1, 1, '')from PostJob where CompanyId = " + id + "";
SqlParameter parameterS = new SqlParameter("@s", s);
SqlParameter parameterD = new SqlParameter("@d", d);
SqlParameter parameterP = new SqlParameter("@p", p);
return _repositoryCustom.FromSql(command, s, d, p).ToList();
}
//repository
public List<PostJobListModel> FromSql(string sql, params object[] objects)
{
return _context.PostJobListModel.FromSql(sql,objects).ToList();
}
This code gives "SQLException Must declar scalar variable “@variableName” " How i do create security command string ?
Edit Answer return _repositoryCustom.FromSql(command, parameterS , parameterD , parameterP ).ToList();
In .Net Core 2.0+ , below code worked for me. No need to pass through SQLParameter class.
// XXSearchResult declared in DbContext class as: public DbQuery XXSearchResults { get; set; }
// udf_textContentSearch is my legacy function in SQL Server database. SELECT * FROM [dbo].[udf_textContentSearch]
You don't set parameters by doing a SqlCommand, you need to pass the parameters in to the
FromSql
statement. From the documentionSo for your code you would do
You should also make
id
a parameter too.While I am calling on SQL stored proc via EF Core, I like to build an array of SqlParameter to help me mash the SQL with params needed in the FromSql call, like this:
Over some iterations, I built up the following to help me compose the SQL:
And to use: