c# Build Error with LINQ syntax in Controller
Hi folks I have the following error on line 11 in this controller code :
public JsonResult GetChartData_IncidentsBySiteStatus(string SiteTypeId, string searchTextSite, string StartDate, string EndDate)
{
if (searchTextSite == null)
searchTextSite = "";
DateTime startDate = DateTime.Parse(StartDate);
DateTime endDate = DateTime.Parse(EndDate);
var sitesQry = _db.Sites;
if (SiteTypeId != "-1")
sitesQry = sitesQry.Where(a => a.SiteTypeId.ToString() == SiteTypeId);
var qry = from i in _db.Incidents
join s in _db.Sites on i.SiteId equals s.SiteId
where s.SiteDescription.Contains(searchTextSite)
&& (i.Entered >= startDate && i.Entered <= endDate)
group s by s.SiteStatus.SiteStatusDescription + "[" + s.SiteTypeId.ToString() + "]"
into grp
select new
{
Site = grp.Key,
Count = grp.Count()
};
return Json(qry.ToList() , JsonRequestBehavior.AllowGet);
}
...........the error is:
Error 7 Cannot implicitly convert type 'System.Linq.IQueryable' to 'System.Data.Linq.Table'. An explicit conversion exists (are you missing a cast?) C:\Documents and Settings\Administrator\Desktop\IRenewables_EMAS\IRenewables_EMAS\Controllers\IncidentController.cs 69 28 Emas.Web
Can anyone suggest a work开发者_JAVA技巧around for this?
thanks
You are trying to assign a base class instance to a sub class instance.
Instead of
var sitesQry = _db.Sites;
try using
IQueryable<Site> sitesQry = _db.Sites;
While @Eranga 's solution may work, I feel as though there are more options and a better explanation available.
Firstly, the reason that you cannot assign the value is because you are trying to assign and implementation of an interface to a concrete type. THis cannot be done because you have no idea what could be implementing that interface, and this means that the it cannot be assigned to something that has a concrete type.
There are multiple options for this. You can do as @Eranga suggests and create a new variable
IQueryable<Site> sitesQry = _db.Sites;
or you can call the .CopyToDataTable
extension method that is exposed by Linq.
sitesQry = _db.Sites.CopyToDataTable();
精彩评论