Dynamic Linq creates multiple queries

c# dynamic-linq linq

Question

The following linq call in plain linq to sql results in 1 SQL query to the database

Table1.Select(t => new {Table2.First().Property1})

But I can't seem to get Dynamic Linq to to the same, the below produces 2 separate queries.

Table1.Select("new(@0.Property1)", Table2.First())

This does not work either

Table1.Select("@0", Table2.First().Property1)

or this

Table1.Select("new(@0 as MyField)", Table2.First().Property1)

What am I missing ?

1
0
5/22/2016 5:43:03 AM

Accepted Answer

Thanks to Jeff's insights the correct query arrangement should be

Table1.Select(t => new {t2 = Table2.First()}).Select("new(t2.Property1)")

which produces a single query call to the DB

0
5/23/2016 2:27:26 AM

Popular Answer

It's generating two separate queries because in that context, Table2.First() is a separate call from the rest of the query. It's not integrated into the generated expression. It's as if you did this:

var first = Table2.First(); // evaluated eagerly due to the First() call
var query = Table1.Select("new(@0.Property1)", first);

You can achieve the desired result if you rewrote it in terms of a cartesian product with the second table.

var query = Table1.SelectMany(t1 =>
        Table2.Take(1).Select(t2 => new { t1, t2 })
    )
    .Select("new(t2.Property1 as MyField)");


Related Questions





Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow