silhouette hustler
silhouette hustler

Reputation: 1763

Return string value from a database

I am trying to get the Patient's Firstname from a database but what I am getting when I run this piece of code is just a Linq expression string instead.

public static string GetPatientName(int bedNumber)
{
        var name = "";

        using (var data = new HospitalDBDataContext())
        {
             if (data.Connection.State == ConnectionState.Closed) 
               data.Connection.Open();

             name = data.Patients.Where(x => x.BedNumber.Equals(bedNumber))
                                 .Select(x => x.Firstname).ToString();

            if (data.Connection.State == ConnectionState.Open) 
               data.Connection.Close();

            data.Dispose();
        }

        return name;
}

What is the way of making this Expression to return the actual value I need?

Upvotes: 0

Views: 559

Answers (3)

wentimo
wentimo

Reputation: 491

name = data.Patients.Where(x => x.BedNumber.Equals(bedNumber))
                    .Select(x => x.Firstname).ToString();

Should be:

name = data.Patients.Where(x => x.BedNumber.Equals(bedNumber))
                    .Select(x => x.Firstname).FirstOrDefault();

You need to actually select .First() or .FirstOrDefault(). Right now you are casting the entire IQueryable statement into a string.

Upvotes: 5

eppsilon
eppsilon

Reputation: 2081

The Where method returns an Enumerable<T> of results (patients), and the Select method returns a new Enumerable<string> with the Firstnames of each patient.

Instead of converting that Enumerable<string> to a string, you need to use a method like Single or First to get one object out of it.

(Single will throw an exception if there is more than one object in the Enumerable<T>, and First will throw an exception if there are no objects in the Enumerable<T>. Use SingleOrDefault or FirstOrDefault if you want null instead of an exception in those cases.)

Upvotes: 1

M.kazem Akhgary
M.kazem Akhgary

Reputation: 19149

The problem is ToString call that gives you the Linq expression

possible solutions. using FirstOrDefault to get first name.

name = data.Patients.Where(x => x.BedNumber.Equals(bedNumber)).Select(x => x.Firstname).FirstOrDefault();

Or use string.Join to get all the names in one string with separator like ,(the first parameter passed to string.join).

name = string.Join(", " ,data.Patients.Where(x => x.BedNumber.Equals(bedNumber)).Select(x => x.Firstname));

Upvotes: 1

Related Questions