简体   繁体   中英

Linq to Entities - Projections against Query Syntax vs Method Syntax

Since LINQ query expression are translated "under the covers" to call the same methods that a corresponding method query would call (at least I think so), I would expect these two queries to return the same type. For some reason though this:

var result = from i in db.Invoices
             select new { i.InvoiceNum };

sets result as an IQueryable<'a> with each member having an InvoiceNum property, while this

IQueryable<string> result2 = db.Invoices.Select(i => i.InvoiceNum);

Is smart enough to return IQueryable<string> (obviously, since that compiles)

Clearly one of my assumptions is wrong, and I was hoping an expert could help me understand a bit better.

(this is EF4, but the same happens with linq-to-objects, and I'm guessing the same would also happen with L2S)

When you write new { } you are creating an anonymous type

try

var result = from i in db.Invoices
             select i.InvoiceNum;

and you will see that it returns the type you expect.

those are not the same, the first one is returning anonymousn type, to make them the same you need to have th first one as:

var result = from i in db.Invoices
         select i.InvoiceNum;

In your first statement, you create an anonymous type with one property named "InvoiceNum". This happens because you use the new { } syntax. That anonymous type is not a String. The equivalent method syntax would be:

var result = db.Invoices.Select(i => new { i.InvoiceNum });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM