简体   繁体   English

Linq to ASP.Net MVC 4中的Sql返回实际的查询字符串

[英]Linq to Sql in ASP.Net MVC 4 returns actual query string

I am trying to get the First and Last Name string values out of my AspNetUsers table for a particuler record (ID). 我试图从我的AspNetUsers表中获取名字和姓氏字符串值,以获得特定记录(ID)。 When I use Linq to Sql, it returns the entire sql query string. 当我使用Linq to Sql时,它将返回整个sql查询字符串。 here is my code: 这是我的代码:

 var user = User.Identity.GetUserId();
            var currentUser = from aspNetUser in db.AspNetUsers
                              where aspNetUser.Id == user
                              select aspNetUser.FirstName + " " + aspNetUser.LastName;

I am trying to populate my User Textbox in my View with the Current Users First and Last Name. 我正在尝试使用当前用户的名字和姓氏在视图中填充用户文本框。 Which I have added as columns to the AspNetUsers Table. 我已将其作为列添加到AspNetUsers表中。 Why does it return this ugly query and not someone's first and last name? 为什么它返回这个丑陋的查询,而不返回某人的名字和姓氏?

it's returning this: 它返回这个:

SELECT     CASE WHEN ([Extent1].[FirstName] IS NULL) THEN N'' ELSE [Extent1].[FirstName] END + N' ' + CASE WHEN ([Extent1].[LastName] IS NULL) THEN N'' ELSE [Extent1].[LastName] END AS [C1]    FROM [dbo].[AspNetUsers] AS [Extent1]    WHERE [Extent1].[Id] = @p__linq__0

Not really sure how you are getting the SQL query back, but you need a single record back from your query. 不太确定如何返回SQL查询,但是您需要从查询中返回一条记录。 Use First/FirstOrDefault like: 使用First / FirstOrDefault,例如:

var currentUser = (from aspNetUser in db.AspNetUsers
                  where aspNetUser.Id == user
                  select aspNetUser.FirstName + " " + aspNetUser.LastName)
                  .FirstOrDefault();

FirstOrDefault would return the first record returned from the result. FirstOrDefault将返回从结果返回的第一条记录。 If there are no records then you will get null back. 如果没有记录,那么您将获得null

You can also use Single \\ SingleOrDefault , since you are querying against ID and there should always be a single record returned. 您还可以使用Single \\ SingleOrDefault ,因为您要查询ID并且始终应该返回一条记录。 But both of them could throw an exception if there are multiple records matching your criteria. 但是,如果有多个符合您条件的记录,它们都可能引发异常。 Use any of them according to your requirement. 根据您的要求使用它们中的任何一个。

you can use FirstOrDefault() to get single record against specific criteria: 您可以使用FirstOrDefault()根据特定条件获取单个记录:

var currentUser = db.AspNetUsers.FirstOrDefault(x=>x.Id == user);

var Name = currentUser.FirstName + " " + currentUser.LastName;

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

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