views:

44

answers:

1

I have an Expression that converts one type of object to another type. The expression is as follows:

public Expression<Func<SQLRepository.ActionType, Model.ActionType>> DBActionTypeToActionType =
(SQLRepository.ActionType at) => new Model.ActionType()
{
    ID = at.OID,
    DisplayName = at.DisplayName
};

I can use the Expression like this:

var linq = (from at in dc.SQLRepositoryDC.ActionTypes select at).Select(DBActionTypeToActionType);

But I'd like to use it like this:

var linq = (from at in dc.SQLRepositoryDC.ActionTypes select DBActionTypeToActionType.Compile().Invoke(at));

I've been looking for a couple days now and I can only find references to doing this in the Where clause. It seems that if I'm able to use the function calls to do this, it should be possible using the query syntax.

The reason it is important to do use the query syntax is that some of the objects that are being selected are composed of many sub-objects and trying to chain them all of the conversions together with the function notation will be much harder to write and maintain.

+2  A: 

It seems that if I'm able to use the function calls to do this, it should be possible using the query syntax.

That's not true. Query notation always goes via a lambda expression. For example

from x in y select z

ends up as

y.Select(x => z)

That means if you've already got an expression tree that you want to pass directly as the argument to Select, you can't use query expressions because there's this extra level of indirection.

Now the options available depend on where you need to apply the predefined expression. You can always use it in the source, and then continue with the query:

var query = from foo in dc.ActionTypes.Select(DBActionTypeToActionType)
            where foo.Stuff
            select foo.Other;

Or using it at the end is easy:

var query = (from bar in dc.ActionTypes
             where bar.Stuff
             select bar).Select(DBActionTypeToActionType);

Does that help at all?

Jon Skeet
Yes, that helps greatly. I had not considered applying the select function to the table _BEFORE_ joining with it, I was stuck on trying to do it after all of data was collected.Thank you very much.
David Burhans