Dev P Dev P - 2 months ago 8
SQL Question

Getting actual value from a column in SQL BD table via linq

I need to be able to retrieve the value stored in a column called

ClientEmail
from a
Client
table in a
TEST
DB. Then I needed to be able to use this value to send out an email e.g:

The following Linq query retrieves the details I need:

var clientEmail = (from c in DB.Clients
where c.ClientID == Convert.ToInt32(Session[Constants.SessionKeys.ClientID])
select new { c.ClientEmail }
).FirstOrDefault();

string clientMailBox = clientEmail.ToString();


Now I want to use the value store in the
clientMailBox
string variable in order to send out an email.

However, the result of the query returns both the name of the column and its value in the following format:

{ ClientEmail = test.dep.team"@testemail.co.uk }


The actual value from that column is:

test.dep.team"@testemail.co.uk


I am expecting to get above value, instead I am getting:

{ ClientEmail = test.dep.team"@testemail.co.uk }


Is there anything I am missing from my query ?

I would be very grateful for any suggestions.

Answer

Don't use ToString() on your anonymous object, but take the property you need.

 string clientMailBox = clientEmail.ClientEmail;

In a projection, if you don't specify a proprety name, it takes the selected property's name.

And FirstOrDefault returns an anonymous object with a ClientEmail string property, not a string.

Another (I would say better in this case) way would be to just select the string property.

var clientEmail = (from c in DB.Clients
                   where c.ClientID == Convert.ToInt32(Session[Constants.SessionKeys.ClientID])
                   select c.ClientEmail)
                   .FirstOrDefault();

Then, clientEmail would be a string (which may be null).

EDIT

Once this is clear, you may use Konstantin Ershov' shorter syntax (which assumes at least .net 4.6 for null conditional operator)