|
-
Jan 27th, 2012, 09:57 AM
#1
Thread Starter
Addicted Member
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.
-
Jan 27th, 2012, 10:40 AM
#2
Thread Starter
Addicted Member
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?
-
Jan 27th, 2012, 11:08 AM
#3
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.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|