3

I want to achieve the following:

return  (from a in db.Tags
    select new TagItem
    {
        ID = a.Id,
        Name = a.Name
    });

..but i don't want to achieve it like that, because i need to use the exact same TagItem construction elsewhere (for a join)

So this is the intention, to call a method that constructs the TagItem for me:

return (from a in db.Tags
    select ConstructTagItem(a));

And the method constructs the object the same way:

private TagItem ConstructTagItem(Tag a)
{
    return new TagItem { ID = a.Id, Name = a.Name};
}

But this gives me the following error:

Method 'TagItem ConstructTagItem(Tag)' has no supported translation to SQL.

Is there any way to achieve this ?

Solution (thanks Daniel Hilgarth):

return db.Tags.Select(ConstructTagItem);

And the method:

private Expression<Func<Tag, TagItem>> ConstructTagItem
{
    get { return a => new TagItem {ID = a.Id Name = a.Name }; }
}

1 Answer 1

3

Yes, there is. You need to use an expression tree like this:

Expression<Func<Tag, TagItem>> constructTagItem = a => return new TagItem
                                                       { ID = a.Id, 
                                                         Name = a.Name};

And then you can use that expression instead of your method:

return db.Tags.Select(constructTagItem);

According to this article you need to use the method chains way of defining your query.

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

4 Comments

I have just figured out i had to use expressions, and then you wrote with this brilliant answer, thanks! ..i just have one question, I will try to explain it in my question, give me a sec
@Frost: IMHO, this should be a new question, because it is something else. I don't think it can be done the way your first example can be done. Basically, you just changed your complete question :) Please create a new question and accept my answer here.
Will do, but i wrote: "because i need to use the exact same TagItem construction elsewhere (for a join)"
@Frost: Yeah, I thought your join would also select a TagItem as the end result and not a NewsTagItem.

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.