简体   繁体   中英

c# LINQ returning all joined results

I want to return a result set from a join on two tables. So far I've joined the table but am having difficulty figuring out the last part (or possibly the whole thing needs rewired).

var x = _context.GameHasPlayers
    .Join(_context.Games, 
        ghp => ghp.GameId,
        g => g.Id,
        (gameHasPlayer, game) => /*What goes here*/ );

In SQL I'd simply write this:

select * from GameHasPlayer ghp
join Game g on g.Id = ghp.GameId

Let's say this should return 2 Games, each with 2 players, so a total of four rows.

It runs if I use in the last line of my c# query:

(gameHasPlayer, game) => new Game { });

But I just get four (as expected) new empty Game classes, so I'm struggling with how I can return the entire result set (ie all 4 rows of both tables joined) - do I need to create some new model/view that combines Game and GameHasPlayer first?

(eg in SQL I could create a view that implements the above SQL query and return a generic dataset or recreate the view c# side?)

----- edit -----

I'm also trying below:

var x = from ghp in _context.GameHasPlayers
    from g in _context.Games
    where g.Id == ghp.GameId
    select (g) // or select (ghp)

which gives me ACTUAL results but only for g or ghp - if I try select (g, ghp) it just doesn't play ball!

You have to understand that C# will need some idea of the structure of the instances your returning. Simply conjoining two otherwise unrelated classes isn't an option, sadly.

Fortunately, that's what the select statement provides you with: a way to create anonymous objects on the fly to store in your result set.
select (g) works because the type of g is known to the compiler. But if you want to join g and ghp , you need to construct a new type:

select(r => new {
   Id = g.Id,
   GameId = ghd.GameId,
   // ...
})

You can use either of the below syntax:

_context.GameHasPlayers.Join(
    _context.Games,
    gameHasPlayer => GameHasPlayer.GameId,
    game => Game.Id,
    (gameHasPlayer, game) => new { GameHasPlayer = gameHasPlayer, Game = game }
)


from ghp in _context.GameHasPlayers
join g in _context.Games on g.Id equals ghp.GameId
select new { GameHasPlayer = ghp, Game = g }

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