开发者

Linq to entity - Call user defined method from query

开发者 https://www.devze.com 2023-02-10 21:15 出处:网络
In my project, i use several linq queries for getting prices list. I need to calculate values based on these prices.

In my project, i use several linq queries for getting prices list. I need to calculate values based on these prices.

Is it possible to call a user method (who can, ideally, be in the entity class) directly from the linq query, for example, doing like this would be perfect

from foo in Foo
select new {
  price = foo.Price,
  priceclass开发者_StackOverflow中文版 = foo.GetClassOfPrice()
}

There would be no data access from GetClassOfPrice, just static code based on the price.

Thank's by advance !


Linq-To-Entities can call only special type of methods defined in conceptual model (EDMX). These methods are called Model defined functions. So if you define your method this way you will be able to call it. You can also check this blog post.


You can only call the method via LINQ to Objects as there is no translation to SQL for the method call. If you materialize the query -- bring it into memory -- first, then do the selection it should work.

var foos = context.Foo.ToList()
                      .Select( f => new
                       {
                            price = f.Price,
                            priceClass = f.GetClassOfPrice()
                       } );

Note that you should perform any conditional logic (Where) before doing the ToList so that you're only transferring the data that you actually need from the DB. I'm using extension methods because it's more natural for me and because you'd need to use the ToList or similar method anyway. I really dislike mixing LINQ syntax with the extension methods.


Unfortunately, this can't be done, because your LINQ query is translated to SQL. And your method isn't known to the so called provider that does this translation.


There are only a few functions that you can call when dealing with linq to entities and they are listed here: http://msdn.microsoft.com/en-us/library/system.data.objects.sqlclient.sqlfunctions.aspx

http://msdn.microsoft.com/en-us/library/system.data.objects.entityfunctions.aspx

0

精彩评论

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