我一直试图搜索谷歌,但无济于事。感觉就像以前被问过,但也许我不是在谷歌搜索我认为我需要的东西。
我希望获得Object
ICollection<T>
Id
个value
属性为public class User {
public int Id { get; set; }
public string Name { get; set; }
public ICollection<Role> Roles { get; set; }
}
public class UserRole {
public int UserId { get; set; }
public int RoleId { get; set; }
}
的{{1}}集合。
我应该用哪种方式编写Linq表达式?
例如:
RoleId
如果我知道User
,我该如何获得所有var roleId = 1;
var users = db.UserRoles.SingleOrDefault(r => r.RoleId == roleId).Roles;
?以下似乎是正确的,它确实给了我我需要的东西:
示例1
var roleId = 1;
var users = db.Users.Where(u => u.UserRoles.Where(r => r.RoleId == roleId)).Users;
但,是否可以反过来获得相同的结果?例如,我试过这个:
示例2
Cannot convert type UserRole to bool
我收到一条消息Users
。
Object-X
?Navigation
,但只知道Object-Y where It's Id is this, then give me Object-X
属性的值,我应该怎么想写这个表达式?
HTTP/1.1 200 OK Content-Type: text/html; charset=utf-8
X-Robots-Tag:noindex, nofollow, nosnippet
Cache-Control: no-cache, no-store, max-age=0, must-revalidate Pragma: no-cache Expires: Mon, 01 Jan 1990 00:00:00 GMT Date: Wed, 14 Feb 2018 00:25:58 GMT
Content-Security-Policy: script-src 'report-sample' 'nonce-9FVKa6PbBSHhVPp1t9CsQgHFpDA' 'unsafe-inline' 'strict-dynamic' https: http: 'unsafe-eval';object-src 'none';base-uri 'self';report-uri https://csp.withgoogle.com/csp/viewer/
X-Content-Type-Options: nosniff X-Frame-Options: SAMEORIGIN
X-XSS-Protection: 1; mode=block Server: GSE
Set-Cookie: DRIVE_STREAM=UMl4FRnEZmE; Domain=.drive.google.com; Path=/; Secure; HttpOnly Alt-Svc: hq=":443"; ma=2592000; quic=51303431; quic=51303339; quic=51303338; quic=51303337; quic=51303335,quic=":443"; ma=2592000; v="41,39,38,37,35"
Accept-Ranges: none Vary: Accept-Encoding
Transfer-Encoding: chunked
”我问,因为我习惯这样思考:“获取`Object-X,其中Object-Y具有此值”。
也许我让这个令人困惑,但我希望有人能帮助清理它。
答案 0 :(得分:5)
如果我知道RoleId,我该如何获得所有用户?
假设角色类具有 RoleId 属性,您可以执行以下操作:
var roleId = 1;
var users = db.Users.Where(q => q.Roles.Any(w => w.RoleId == roleId));