i have written the following query and it is giving error Unable to cast object of type
System.Data.Objects.ObjectQuery'[ITClassifieds.Models.Viewsearch]' to type 'ITClassifieds.Models.Viewsearch'.
my code is as follows
if (zipcode.Contains(","))//opening of zipcode conatins comma
{
do
{
zipcode = zipcode.Replace(" ", " ");
zipcode = zipcode.Replace(", ", ",");
} while (zipcodecity.Contains(" "));
char[] separator = new char[] { ',' };
string[] temparray = zipcode.Split(separator);
var zipcd = (from u in db.ZipCodes1
where u.CityName == temparray[0] && u.StateAbbr == temparray[1] && u.CityType == "D"
select new Viewsearch
{
Zipcode = u.ZIPCode
}).Distinct();
Viewsearch vs = (Viewsearch)zipcd;
if (zipcd.Count() > 0)
{
zipcode = vs.Zipcode;
locations = "";
}
else
{
tempStr = "";
zipcode = "";
}
}
The
Distinctmethod returns an enumerable collection (in your case, andObjectQuery<T>, which may contain more than one element. You can’t typecast that directly to an item in the collection, you need to use one of the IEnumerable methods to get it:SingleOrDefaultwill throw an exception if there is more than one item in the collection; if that’s a problem, you can also useFirstOrDefaultto grab the first item, as one example.Also, unrelated to your question, but you don’t need the temporary array variable for your string separators. The parameter to the Split method is a
paramsarray so you can just call it like this: