Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq to SQL construct a custom object externally

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 }; }
}
like image 654
Frost Avatar asked Dec 11 '25 10:12

Frost


1 Answers

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.

like image 144
Daniel Hilgarth Avatar answered Dec 14 '25 07:12

Daniel Hilgarth



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!