I have an IQueryable of MyType obtained via EF 4.1.
I am applying filters via linq in the form of a where clause, One of which will filter based on distance from a given zip code.
MyType has a ZipCode property and I need to call a method which computes the distance between the MyType zip codes and my given zip code.
I have tried the following, which compiles, but throws an error at runtime.
myTypes = myTypes.Where(x => GetDistance(x.Zip, givenZip) < 10);
How can I accompish this?
EDIT
My Distance method returns a double that represents the distance in miles
public double Distance(Position position1, Position position2)
{
}
Position is a struct containing doubles for lat and long
This should work in Linq to Objects if GetDistance()
returns a boolean - it will not work with Linq to Entities since it will try to map your method to a SQL equivalent, which of course there is none.
As a crude workaround you could use AsEnumerable()
but that would materialize all your types so is not recommended if your table is larger:
myTypes = myTypes.AsEnumerable()
.Where(x => GetDistance(x.Zip, givenZip) < 10);
Another way would be to map Zip codes to geographic locations in the database and use those locations directly with the soon to be supported spatial data types - this is probably the best approach in my opinion, but not production-ready. Of course if you are restricted to just SQL Server you could just use a store query directly to use geo-locations - but that would work around EF.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With