1
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?

0

4 Answers 4

4

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.
Sign up to request clarification or add additional context in comments.

Comments

0

Just fetch like this

var user = us.SingleOrDeafult();

if(user != null)
{
    var fn = user.firstName;
}

1 Comment

Instead of the if, you can use the null-propogation operator: var fn = user?.firstName;
0
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.

Comments

0

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;

.....

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.