Swapna Swapna - 17 days ago 4
JSON Question

How to get json data in return using mvc and entity framework

getting error at orderby g.datetime
error

Severity Code Description Project File Line Suppression State
Error CS1061 'IGrouping' does not contain a definition for 'datetime' and no extension method 'datetime' accepting a first argument of type 'IGrouping' could be found (are you missing a using directive or an assembly reference?) waterleveltesting c:\users\kernel\documents\visual studio 2015\watertower\waterleveltesting\waterleveltesting\Controllers\waterController.cs 22 Active

id waterlevel datetime towerid
1 25 2016-09-21 01:10:00.000 1
2 33 2016-09-21 01:11:00.000 2

op- [{"towerid":"1","waterlevel":25,"datetime":"Nov 09, 2016 07:02:25PM"},{"towerid":"33","waterlevel":22,"datetime":"Nov 09, 2016 07:02:25PM"}]


My code:

public ActionResult Getwaterlevel()
{
using (waterlevel_Entities DB = new waterlevel_Entities())
{
var wt = from w in DB.watertowerlevels
group w by w.towerid into g
orderby g.datetime
select new
{
towerid = g.Key,
waterlevel = g.FirstOrDefault().waterlevel,
datetime = g.FirstOrDefault().datetime.ToString("MMM yyy")
};


return Json(wt.ToList(), JsonRequestBehavior.AllowGet);


}

}

Answer

Try to use this one:

        var wt = from w in DB.watertowerlevels
                 group w by w.towerid into g
                 orderby g.datetime
                 select new { towerid = g.Key, waterlevel = g.FirstOrDefault().waterlevel,
                 datetime = g.FirstOrDefault().datetime};


 return  Json(wt.ToList(), JsonRequestBehavior.AllowGet);