Ben
Ben

Reputation: 383

LINQ Only parameterless constructors and initializers are supported in LINQ to Entities

I am getting an error using the query below, using EF + LINQ

 var model = (from c in _db.Accounts
              let geo = new GeoCoordinate(Convert.ToDouble(c.Latitude.Value), Convert.ToDouble(c.Longitude.Value))
              where ((geo.GetDistanceTo(CurrentCoord) / 1000) < 3) 
              orderby c.Name
              select new CompanyVM
              {
                  Name = c.Name,
                  ... 
              }).ToList();

Runtime error:

Only parameterless constructors and initializers are supported in LINQ to Entities.

Can someone explain why it is failing?

Upvotes: 1

Views: 2433

Answers (1)

MarcinJuraszek
MarcinJuraszek

Reputation: 125610

Entity Framework tries to translate your LINQ query into SQL query that can be executed against the database. Because of that you can't use GeoCoordinate in your query.

Even if the constructor worked Convert.ToDouble call would fail, because it can't be translated into SQL either.

You might want to look into using Spatial Data in SQL and Entity Framework.

Or you might want to write your own version of Haversine formula (that's the one used by GetDistanceTo within your LINQ query. Entity Framework should handle math quite well.

Upvotes: 2

Related Questions