Reputation: 91
var us = from user in conteks.Tabel_User
where user.user_id == userID
select user
How can i get data from each column if the query give 1 row in result?
Upvotes: 1
Views: 1317
Reputation: 65978
You can try as shown below.
Note : If you consider about the Performance then FirstOrDefault()
method is the best.
var us = from user in conteks.Tabel_User
where user.user_id == userID
select user
var userObject = us.FirstOrDefault();
Then :
var firsName = userObject.FirstName;
var lastName = userObject.LastName;
.....
Upvotes: 0
Reputation: 7672
If you are sure that the query will give you exactly one row result, the use .Single
method. It will throws an eror if your query resulting zero or more than one result.
var us = from user in conteks.Tabel_User
where user.user_id == userID
select user
var singleUser = us.Single();
//get name, ssn, etc
var name = singleUser.Name;
var ssn = singleUser.Ssn;
I will explain each method mentioned here.
Single()
. It will give you the row from your single row query. If your query resulting in zero or more than one row, then it will throw an error.SingleOrDefault()
. It will give you the row from your single row query. If your query resulting in zero rows, it will give you default of the type, null
for reference type. And if your query resulting in more than one row, it will throw an error.First()
. It will give you first row if your query, of course if you apply it to single row query, then it will return that row. If your query resulting in
zero row, then it will give you an error.FirstOrDefault()
. The safest method. It will give you first row if your query return row(s), and give you the default of the type (null
for reference type) if your query return zero rows.Upvotes: 4
Reputation: 63105
var us= (from user in conteks.Tabel_User
where user.user_id == userID
select user).FirstOrDefault();
will give you the user object and then you can select each column by us.<columnName>
, you may need null check before accessing object properties if there is a posiblility of no records found for the serarch criteria.
Upvotes: 0
Reputation: 609
Just fetch like this
var user = us.SingleOrDeafult();
if(user != null)
{
var fn = user.firstName;
}
Upvotes: 0