简体   繁体   English

mvc5中的c#Linq查询返回的是列名而不是值

[英]c# Linq Query in mvc5 is returning the column name instead of value

I am doing an assignment using MVC5, I am trying to create a query using Linq which will return the logged in users "StudentId" from the "AspNetUsers" table. 我正在使用MVC5进行分配,我正在尝试使用Linq创建查询,该查询将从“ AspNetUsers”表返回登录用户“ StudentId”。 The code I have to try do this is, 我必须尝试执行的代码是

string currentUser = User.Identity.GetUserId();
            string getStudentId = (from a in db.Users
                                   where a.Id.Equals(currentUser)
                                   select a.StudentId).ToString();

This is setting the string value to "StudentId;" 这是将字符串值设置为“ StudentId;”。 which is the name of the column. 这是列的名称。 (The ID is the default AspNetUsers table Data type which is nvarchar(128) ). (该ID是默认的AspNetUsers表数据类型,它是nvarchar(128))。 Any help on where I am going wrong is much appreciated. 非常感谢我在哪里出错了。

You'll need to execute the query first: 您需要先执行查询:

string getStudentId = (from a in db.Users
                               where a.Id.Equals(currentUser)
                               select a.StudentId).First().ToString();

One solution Might be 一种解决方案可能是

string currentUser = User.Identity.GetUserId();
string studentId;
studentId=db.Users.SingleOrDefault(o=>o.Id==currentUser).Select(o=>o.StudentId.ToString());

I tried your code with minor modifications below: (I substituted your StudentId column with my UserName column, and the viewbag shows the correct UserName on the view page) 我尝试对您的代码进行以下较小的修改:(我用您的UserName列替换了StudentId列,并且viewbag在视图页面上显示了正确的UserName)

        string currentUser = User.Identity.GetUserId();
        var getStudentId = (from a in db.Users
                               where a.Id.Equals(currentUser)
                               select a.UserName).FirstOrDefault().ToString();

        ViewBag.TestUser = getStudentId;

[ Update ] [更新]

I am assuming that your StudentId column is in your Users table. 我假设您的StudentId列在“用户”表中。

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

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