0

I'm trying to return a value using LINQ but instead I'm returning the actual query.

Here is my code:

var email = from p in dbContext.People
            where p.UserId == UserId
            select new { p.Email };
Contact.Email = email.ToString();

I want to get the actual email address of the user but instead I'm getting the query string back.

"SELECT [Extent1].[UserId] AS [UserId], [Extent1].[Email] AS [Email]
  FROM [dbo].[Person] AS [Extent1] WHERE [Extent1].[UserId] = @p__linq__0"
Salah Akbari
  • 39,330
  • 10
  • 79
  • 109
Smac
  • 391
  • 2
  • 10
  • 28
  • 4
    select p.Email. Is the new { .. } necessary? – Fredrik Sep 11 '17 at 11:49
  • Just a quick hint, you can shorten this code to `dbContext.People.FirstOrDefault(p.UserId == UserId);`, assuming that `dbContext.People` derives from `IEnumerable`. – Ian H. Sep 11 '17 at 11:52

1 Answers1

3

Use FirstOrDefault. It returns the first element of a sequence, or a default value if the sequence contains no elements.:

var email = (from p in dbContext.People
                        where p.UserId == UserId
                        select new { p.Email }).FirstOrDefault();

Also if you only want the Email to be returned you can simply return it and there is no need to use an anonymous type for this purpose.

var email = (from p in dbContext.People
                    where p.UserId == UserId
                    select p.Email).FirstOrDefault();
Salah Akbari
  • 39,330
  • 10
  • 79
  • 109
  • 3
    Note that you can omit the `select new { p.Email }` if you **only** want the email and not an anonymous type. – Ian H. Sep 11 '17 at 11:50
  • Also don't forget that FirstOrDefault() will potentially return null if a record doesn't exist, so you need to determine whether it is best for your particular use case to use First() which would potentially produce an exception if a matching record doesn't exist or do a null check before trying to use the returned object. – Kyle Burns Sep 11 '17 at 11:51
  • This worked thanks. @KyleBurns yes Im doing a null check before this code runs. – Smac Sep 11 '17 at 11:55