views:

39

answers:

1

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

+8  A: 

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.

Jon Skeet
Hi Jon. Thanks for fixing the code layout in my post - i'm guessing I should have indented each line of code separately?
ben
And thanks, of course, for the answer. I'd have never have guessed that so your input is much appreciated. Is there a time and place for Lambda vs. LINQ - I'm confused when to use them.
ben
@ben: You need to understand that query expressions and the dot notation (or whatever you want to call them) are equivalent - or rather, every query expression is equivalent to dot notation, as it's effectively translated that way, but not every dot notation query is representable as a query expression. Use whichever is more readable for the particular example.
Jon Skeet
Ok, thanks Jon. Appreciated!
ben
@jon: You mentioned that it's slightly odd to join and ignore the table I'm joining to. I'm using the join to filter the results - like you would in SQL. Is this acceptable in EDM?
ben
@ben: Oh it's *acceptable* - it's just not something I've personally had to do much.
Jon Skeet