eka808
eka808

Reputation: 2317

Linq to entity - Call user defined method from query

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 = foo.GetClassOfPrice()
}

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

Thank's by advance !

Upvotes: 5

Views: 5694

Answers (4)

Ladislav Mrnka
Ladislav Mrnka

Reputation: 364249

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.

Upvotes: 5

Aducci
Aducci

Reputation: 26634

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

Upvotes: 1

tvanfosson
tvanfosson

Reputation: 532445

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.

Upvotes: 4

Daniel Hilgarth
Daniel Hilgarth

Reputation: 174279

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.

Upvotes: 1

Related Questions