Reputation: 9234
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
Upvotes: 5
Views: 10951
Reputation: 9209
Assuming:
List<myType> myTypes;
try:
myTypes = myTypes.Where(x => GetDistance(x.Zip, givenZip) < 10).ToList();
Upvotes: 0
Reputation: 160852
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.
Upvotes: 6
Reputation: 39898
This will throw an error because the runtime tries to convert your expression tree into SQL. The function 'GetDistance' cannot be converted.
Have a look at Model Defined Functions. They allow you to define a custom function in your edmx which you can execute when building queries.
Upvotes: 3