Jean-Francois
Jean-Francois

Reputation: 1949

How call a custom method in lambda expression . I Use Entity Framework 4 . Stored expression error

Is it possible to call a custom method in a lambda expression.?

//Address a : It's an Entity
public string AddressConstructor(Address a)
{
    return a.City + "," + a.Province;
}



var Test = _db.MyTableTest.Select( t => new ViewModel
                                   {
                                      MyID = t.ID,
                                      StringAddress = AddressConstructor(t.Addr)
                                   };

Upvotes: 1

Views: 1525

Answers (2)

Jeff
Jeff

Reputation: 36573

You should be able to accomplish this using LINQKit to inline your expression into the expression tree.

http://www.albahari.com/nutshell/linqkit.aspx

This will cause the concatanation you're attempting to be run on the SQL Server, not in memory (as described in the other answer). SQL Server of course knows how to concatanate strings, but if your AddressConstructor did something else that SQL Server doesn't understand, then this approach would not work and you would indeed need to perform your custom method in memory using the approach described in the other answer.

Essentially LINQKit will flatten the tree so it actually gets executed as:

    var Test = _db.MyTableTest.Select( t => new ViewModel
 {
      MyID = t.ID,
      StringAddress = t.Addr.City + "," + t.Addr.Province
 };

which EF should have no problem executing (and the concatenation should happen on the SQL Server).

Upvotes: 3

Thomas Levesque
Thomas Levesque

Reputation: 292405

You need to call AsEnumerable so that the projection is executed locally:

var Test = _db.MyTableTest.AsEnumerable()
                          .Select( t => new ViewModel
                                   {
                                      MyID = t.ID,
                                      StringAddress = AddressConstructor(t.Addr)
                                   };

Otherwise, the Queryable.Select method is used instead of Enumerable.Select, which causes Entity Framework to try to translate the lambda expression to a SQL query (which of course is not possible in that case)

Upvotes: 1

Related Questions