How to pass parameters to DbSet.SqlQuery Method in Entity Framework

前端 未结 2 960
予麋鹿
予麋鹿 2021-02-05 09:19

I am trying to execute a RAW SQL statement in Entity Framework which takes some parameters. The method I am using is from DbSet.SqlQuery

I am confused on how to construc

相关标签:
2条回答
  • 2021-02-05 09:56

    The above answers are correct but since the signature for SqlQuery is SqlQuery(sql:String, params object[] parameters), you can simplify the code and give it a more natural feel by using:

    context.SqlQuery(sql, latParam, lngPara);
    

    This would be perfectly legal without having to array it first.

    0 讨论(0)
  • 2021-02-05 10:08

    I ended up cleaning up my method's parameters so they wouldn't be the same as my database columns which was not very clear. The ObjectParameter does not support the @ symbol, so that didn't work. I ended up with the following solution:

    public ActionResult APILocation(string latitude, string longitude)
    {
    
     string SQL = "select * from (select *, Distance = ((ACOS(SIN({0} * PI() / 180) * SIN(lat * PI() / 180) + COS({0} * PI() / 180) * COS(lat * PI() / 180) * COS(({1} - long) * PI() / 180)) * 180 / PI()) * 60 * 1.1515) from dbo.Parish) t where Distance < 10 order by Distance asc";
    
         SqlParameter latParam = new SqlParameter("lat", latitude);
         SqlParameter lngParam = new SqlParameter("long", longitude);
         object[] parameters = new object[] { latParam , lngParam };
    
         var stores = db.Store.SqlQuery(SQL, parameters);
    
          return Json(stores, JsonRequestBehavior.AllowGet);
    
    }
    

    I also had to select * in my sub-select because it was trying to map to my entity which it couldn't since I was just returning one column and not everything. This solution proved to work for me!

    Ultimately, the whole object[] parameters can be done like this:

     SqlParameter latParam = new SqlParameter("latitude", latitude);
     SqlParameter lngParam = new SqlParameter("longitude", longitude);
     object[] parameters = new object[] { latitude, longitude };
    

    Thanks hwcverwe for your help.

    Flea

    0 讨论(0)
提交回复
热议问题