简体   繁体   中英

Why does my Lambda query return an anonymous type versus Linq's strongly-typed return value?

Ok, bear with me... hadn't done any Linq or Lambda until a couple of days ago :)

I'm using C# and the ADO.NET Entity Framework. I want to query my model and get back a List of objects based on a relationship.

Here's my code:

var query = db.Achievements.Join
 (
 db.AchievementOrganisations,
 ach => ach.AchievementId,
 ao => ao.AchievementId,
 (ach, ao) => new { Achievement = ach }
 );

var query2 = from s in db.Achievements
 join h in db.AchievementOrganisations
 on s.AchievementId equals h.AchievementId
 select s;

(sorry about the formatting)

My question is why does the first query, which I believe is a Lambda Expression, return an Anonymous Type:

{System.Data.Objects.ObjectQuery<<>f__AnonymousType1<MyApp.Models.Achievement>>}

...but the second query (a LINQ query) I get a strongly-typed value back:

{System.Data.Objects.ObjectQuery<MyApp.Models.Achievement>}

Why is this?

Cheers,

Ben

This bit is the problem in the first call:

(ach, ao) => new { Achievement = ach }

You're creating a new anonymous type with an Achievement property of type Achievement .

I suspect you just want:

(ach, ao) => ach

... although it's slightly odd to do a join and ignore the table you're joining with.

Basically, whenever you see new { ... } that means an anonymous type. (Not to be confused with new[] { ... } which builds an array with an inferred element type, or new List<string> { ... } etc which will build a new List<string> with the given contents.

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