开发者

Entity Framework 4: Math.Sin()-function

开发者 https://www.devze.com 2023-01-10 15:47 出处:网络
is there an possibility to call the Math.Sin()-function in a Linq To Entites (Entity Framework 4) -Query?

is there an possibility to call the Math.Sin()-function in a Linq To Entites (Entity Framework 4) -Query?

I've read, that the current Entity Framework 4 doesn't implement this function.

Maybe there's a workaround to this sol开发者_如何学Cve problem?

(I don't want to invite all entries in the memory.)

Thanks and best regards


Several functions that (usually) have obvious SQL counterparts, like Math.Sin can't be used directly in Entity Framework queries. Presumably this is because they can't be reliably translated to different SQL implementations. A ton of MSSQL-specific functions are, however, exposed as static methods in the class System.Data.Objects.SqlClient.SqlFunctions. They throw exceptions if you call them directly, but are translated into the proper SQL if used in a LINQ query.

See this blog post about the magic that's happening under the covers (namely the EdmFunction attribute).


It is certainly possible to use such function starting with EF4. In EF4, EF team introduced SqlServer functions that can be consumed in linq. You should alway consider using canonical functions cuz they are database agnostic and every vendor should convert those functions to store specific equivalent. However when such functions are not available, you can resort to SqlServer namespace (ESQL) or SqlFunctions for linq

from l in db.Locations select SqlServer.Sin(l.Latitude) + SqlServer.power(l.Longitutde)

I cover several of these options in my functions chapter in my book. Specifically you can look at 11-10 recipe Calling database function in esql 11-11 Calling Database Function in LINQ


Unfortunately it's impossible to call Math.Sin in a LinqToEntities query (or Entity SQL query).

The only way to accomplish this without resorting to retrieving all objects first, is to write a SQL query that does what you want and call it via ObjectContext.ExecuteStoreQuery. This isn't as bad as it sounds because you can still get back typed results.


EDIT: After reading the other answers, it appears that it is possible to call these types of functions (SqlFunctions contains 44 functions with various overloads). I leave my original answer as is because it's another way of achieving the same result.

0

精彩评论

暂无评论...
验证码 换一张
取 消