mcintyre321
mcintyre321

Reputation: 13316

How can I return a joined table as an enumerable on an anonymous return type in linq to sql?

I'd like to return an object with the following signature

class AnonClass{
    string Name {get;}
    IEnumerable<Group> Groups {get;}
}

I have tried the following query, but g only returns a single entity, not all the joined entities

var q = from t in dc.Themes
join g in dc.Groups on t.K equals g.ThemeK 
select new {t.Name, Groups = g};
return q.ToArray();

but this returns

class AnonClass{
   string Name {get;}
   Group Groups{get;}
}

What is the correct linq query to use?

Upvotes: 1

Views: 173

Answers (2)

James Curran
James Curran

Reputation: 103605

If you have the Foreign Key set up correctly, then it should be:

var q = from t in dc.Themes
select new {t.Name, Groups = t.Groups};

Upvotes: 1

Jon Skeet
Jon Skeet

Reputation: 1504182

I think you want "join into" instead of just "join":

var q = from t in dc.Themes
        join g in dc.Groups on t.K equals g.ThemeK into groups
        select new { t.Name, Groups=groups };

(That's completely untested, however - worth a try, but please verify carefully!)

Upvotes: 1

Related Questions