5

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 !

2
  • yep and this don't works Commented Feb 17, 2011 at 13:41
  • That would have been valuable information to include in your question :) Commented Feb 17, 2011 at 15:19

4 Answers 4

5

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.

Sign up to request clarification or add additional context in comments.

Comments

4

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.

Comments

1

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.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.