简体   繁体   English

Linq查询未从数据库字段返回值

[英]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. 我正在使用this.Context.User.Identity.Name返回登录的用户,但是它返回的是电子邮件而不是用户名。 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. 从这个我希望URL看起来像网站/用户/用户名,因此想要获得用户名而不是电子邮件。

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. 我希望linq查询能够找到包含电子邮件地址的行,然后拉出Username并将其存储在var user中。 what it really equals is System.Data.Entity.Infrastructure.DbQuery 它真正等于的是System.Data.Entity.Infrastructure.DbQuery

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.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM