Ultigma
Ultigma

Reputation: 535

Linq Query not returning value from database field

I literally have no idea why this isn't querying the way I expect it to query, I am however new to programming but in my head it seems right.

I am using this.Context.User.Identity.Name to return the logged in user however it returns an email not the username. Here is the script in it's context.

@Html.ActionLink("My Account", "Users", new { id = this.Context.User.Identity.Name  },     false) @: | @Html.ActionLink("Logout", "Logout", "Users") 

from this I want the url to look like website/Users/Username hence wanting to get username instead of email.

The query:

Project1.Models.DBContext db = new Project1.Models.DBContext();
//save u.Username in var user where u.Email == user_logged_in_email

var user = from u in db.Users
           where u.Email == this.Context.User.Identity.Name
           select u.Username;

I was hoping that the linq query would find the row that contained the email address and then pull the Username out and store it in var user. what it really equals is System.Data.Entity.Infrastructure.DbQuery

Upvotes: 0

Views: 1366

Answers (1)

Joe Brunscheon
Joe Brunscheon

Reputation: 1989

You need to enumerate that query to get the user:

var user = (from u in db.Users
           where u.Email == this.Context.User.Identity.Name
           select u.Username).SingleOrDefault();
//SingleOrDefault will return null if no user is found, so you need to check for that before operating upon the user object.

Upvotes: 1

Related Questions