Using parameters with EntityFramework and `FromSql`

后端 未结 3 571
生来不讨喜
生来不讨喜 2021-01-04 06:37
     public List GetPostsByCompanyId(int id, int s, int d, int p)
{
    string command = @\"select Id,Title,Cities = STUFF(
     (SELECT  \',         


        
3条回答
  •  暖寄归人
    2021-01-04 07:05

    You don't set parameters by doing a SqlCommand, you need to pass the parameters in to the FromSql statement. From the documention

    You can also construct a DbParameter and supply it as a parameter value. This allows you to use named parameters in the SQL query string+

    var user = new SqlParameter("user", "johndoe");
    
    var blogs = context.Blogs
        .FromSql("EXECUTE dbo.GetMostPopularBlogsForUser @user", user)
        .ToList();
    

    So for your code you would do

    public List 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, parameterS, parameterD, parameterP).ToList();
    }
    

    You should also make id a parameter too.

提交回复
热议问题