I am trying to return LINQ results serialized to JSON from an ASMX Webservice. As far as I know this should work so I must be missing something.
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string GetCitiesForAffiliate(string aff)
{
XDocument centerXml = XDocument.Load(HttpContext.Current.Server.MapPath("~/App_Data/Centers.xml"));
var query = (from center in centerXml.Descendants("Center")
where center.Element("ServiceArea").Value == aff
orderby center.Element("City") ascending
select new {
City = center.Element("City")
}).Distinct();
JavaScriptSerializer serializer = new JavaScriptSerializer();
string json = serializer.Serialize(query);
return json;
}
The serializer.Serialize(query) line throws an ArgumentException: At least one object must implement IComparable. I thought maybe the problem was that I was selecting an anonymous object but typing the object didn’t do it. I’m sure I’m just missing something stupid?
Interestingly, this previous version worked fine:
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string GetCitiesForAffiliate(string aff)
{
TextFileReader reader1 = new TextFileReader(HttpContext.Current.Server.MapPath("~/App_Data/Centers.csv"), ",");
var query = (from cols in reader1
where cols[3].Equals(aff)
orderby cols[2] ascending
select new { City = cols[2] }).Distinct();
JavaScriptSerializer serializer = new JavaScriptSerializer();
string json = serializer.Serialize(query);
return json;
}
The TextFileReader object is from this CodeProject project.
Looks like lazy query execution got you. LINQ doesn’t execute your query until the last possible moment. In this case that is on the serialization line. The problem is in your query and not the serializer.
The problem looks like when you are doing an order by you are getting back an XElement object (which appearantly doesn’t implement IComparable) and blows up trying to compare them.
I would do your select first then order the results.