Results 1 to 3 of 3

Thread: How to get data from a LINQ to SQL object

  1. #1

    Thread Starter
    Addicted Member
    Join Date
    Jan 2010
    Location
    San Marcos, TX
    Posts
    177

    How to get data from a LINQ to SQL object

    I have the following line of code:

    Dim clients = From client In db.clients
    Select client
    Where client.ClientID = id

    In debugging, the clients object populates perfectly, but how can get get data from the clients object? Like if the clients object has a FirstName property, how can I set a textboxes text property to that property from the clients object?

    I thought it'd be something like:

    tbClientFirstName.Text = clients.FirstName

    But that doesn't work.

  2. #2

    Thread Starter
    Addicted Member
    Join Date
    Jan 2010
    Location
    San Marcos, TX
    Posts
    177

    Re: How to get data from a LINQ to SQL object

    I got it working with:

    For Each client In clients
    tbClientFirstName.Text = client.FirstName
    Next

    Is there an easier way?

  3. #3
    Raging swede Atheist's Avatar
    Join Date
    Aug 2005
    Location
    Sweden
    Posts
    8,018

    Re: How to get data from a LINQ to SQL object

    In your first post, you write that you thought you would be able to write something like this:
    Code:
    tbClientFirstName.Text = clients.FirstName
    But that would only be correct if clients referred to one client. Since clients is the result of a linq query, it is possible that it contains more than one entity. In your case, it probably never will as you are using where to pick a client by ID. However, the CLR doesnt know this.
    What you can do, is call First or FirstOrDefault on the clients collection:
    Code:
    Dim clients = (From client In db.clients
    Select client
    Where client.ClientID = id).First()
    Now, clients will refer to the first (and only) client in the result. If however, there is a possibility that no clients are returned from the query, calling First on it will throw an exception and you should use FirstOrDefault instead which will return Nothing if that where to happen.
    Rate posts that helped you. I do not reply to PM's with coding questions.
    How to Get Your Questions Answered
    Current project: tunaOS
    Me on.. BitBucket, Google Code, Github (pretty empty)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width