[英]Can't figure out the right linq query for this
I want to generate a list in my datagrid view box. 我想在我的datagrid视图框中生成一个列表。 I have the userId, uId , and i want to at first search for the user in the database using the id and then display the user's corresponding username and rolename.
我有userId, uId ,我想首先使用ID在数据库中搜索用户,然后显示用户的相应用户名和角色名。 How can i do this?
我怎样才能做到这一点? Below, i've attempted to search for user using UserId, but since i'm new to this i know that the rest of the code after brackets isn't right.
在下面,我尝试使用UserId搜索用户,但是由于这是我的新手,我知道方括号后的其余代码不正确。 I could use some help with the syntax.
我可以在语法上使用一些帮助。 Thanks
谢谢
var list = _db.AspNetUserRoles.FirstOrDefault(w => w.UserId == uId)
{
w.AspNetUser.UserName,
w.AspNetRole.Name
});
dataGridView1.DataSource = list;
Use the Where
clause instead of FirstOrDefault
, because FirstOrDefault
returns the first element of a sequence. 使用
Where
子句代替FirstOrDefault
,因为FirstOrDefault
返回序列的第一个元素。 After the Where
clause use Select
to make a anonymous class with UserName
and Name
properties: 在
Where
子句之后,使用Select
来创建一个具有UserName
和Name
属性的匿名类:
var list = _db.AspNetUserRoles.Where(w => w.UserId == uId).Select(w => new
{
UserName = w.AspNetUser.UserName,
Name = w.AspNetRole.Name
}).ToList();
dataGridView1.DataSource = list;
As lan Mercer said FirstOrDefault
returns first or default (single) value, if you want list of elements which satisfies condition provided by you then use where
. 正如lan Mercer所说,
FirstOrDefault
返回第一个或默认(单个)值,如果您想要满足您提供的条件的元素列表,请使用where
。
var list = _db.AspNetUserRoles.Where(w => w.UserId == uId)
{
Uname = w.AspNetUser.UserName,
Name = w.AspNetRole.Name
});
dataGridView1.DataSource = list;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.