none
Help with Find and Include Linq RRS feed

  • Question

  • Please bare with me. I am trying to understand the Linq language. I am to to this.

    Here is the codefirstMVC codes with 2 tables related to each other by TeamName key.

    ======================================================

    Function Index() As ActionResult
                Dim players = db.Players.Include(Function(p) p.Team)
                Return View(players.ToList())
            End Function

            ' GET: Players/Details/5
            Function Details(ByVal id As Integer?) As ActionResult
                If IsNothing(id) Then
                    Return New HttpStatusCodeResult(HttpStatusCode.BadRequest)
                End If
                Dim player As Player = db.Players.Find(id)

    ' to do

                add  db.Players.Include(Function(p) p.Team) to the linq

    'end to do

                If IsNothing(player) Then
                    Return HttpNotFound()
                End If
                Return View(player)
            End Function

    =====end of code===============================

    I would like to combind the linq statements together:

     Dim player As Player = db.Players.Find(id)

     db.Players.Include(Function(p) p.Team)

    but I don't know how.  Can any give me some clue where to start?

    The logic is this:

    SELECT        dbo.Players.PlayerId, dbo.Players.LastName, dbo.Players.FirstName, dbo.Players.Position, dbo.Players.TeamName, dbo.Teams.City, dbo.Teams.Province
    FROM            dbo.Players INNER JOIN
                             dbo.Teams ON dbo.Players.TeamName = dbo.Teams.TeamName
    WHERE        (dbo.Players.PlayerId = 1)

    Thank you.

    Monday, June 10, 2019 5:01 PM

Answers

  •  Dim player = db.Players.Include(Function(p) p.Team).ToList.Find(Function(x) x.PlayerId = id)

    This above code works.:)

    • Marked as answer by d052057 Tuesday, June 11, 2019 1:57 AM
    Tuesday, June 11, 2019 1:57 AM

All replies

  • Did you try db.Players.Include(Function(p) p.Team).Find(id)?

    If Find does not work, then consider SingleOrDefault that filters by PlayerId.

    Monday, June 10, 2019 6:22 PM
  • Tried it. Id doesn't work.
    Monday, June 10, 2019 8:38 PM
  •  Dim player = db.Players.Include(Function(p) p.Team).ToList.Find(Function(x) x.PlayerId = id)

    This above code works.:)

    • Marked as answer by d052057 Tuesday, June 11, 2019 1:57 AM
    Tuesday, June 11, 2019 1:57 AM