[英]Asp.Net .Net 5 Lambda LINQ get the role name associated with the user account in Asp.Net identities
I am using Asp.Net .Net5 with Entity framework 5我正在使用带有实体框架 5 的 Asp.Net .Net5
I have 3 tables我有 3 张桌子
My current LINQ code returns back all data from users and userRoles, but none from the aspnetrole table.我当前的 LINQ 代码返回来自用户和 userRoles 的所有数据,但没有来自 aspnetrole 表的数据。 I want it to return back the user and the role they are currently assigned so that I can see if they are admin or standard.
我希望它返回用户和他们当前分配的角色,以便我可以查看他们是管理员还是标准。
public async Task<IList<User>> GetAllEnabledAccounts()
{
var users = await _context.Users
.Where(u => u.IsEnabled == true)
.Include(r => r.UserRoles)
.ToListAsync();
return users;
}
aspnetuser table aspnetuser 表
id | username
--------------
1 | Jim
2 | Harry
aspnetRoles aspnet角色
id | name
----------
1 | admin
2 | standard
aspnetuserRoles aspnetuser角色
userId | roleId
----------------
1 | 1
2 | 2
When querying it should return back the user Jim showing that he is admin and Harry showing that he is a standard account.查询时应该返回用户 Jim 表明他是管理员,而 Harry 表明他是标准帐户。 How do I type up the LINQ query to output the information correctly?
如何键入 LINQ 查询以正确输出信息?
According to your code, I suppose the aspnetuser and aspnetRoles was configured many-to-many relationship , right?根据您的代码,我想 aspnetuser 和 aspnetRoles 配置为多对多关系,对吧? If that is the case, you could refer to the following sample, and using the InClude , ThenInClude and SelectMany method to query the related entities.
如果是这种情况,您可以参考以下示例,并使用InClude 、 ThenInClude和SelectMany方法查询相关实体。
Sample code as below (The Authors and Books table contains many to many relationship, BookAuthor is the join table, similar with the aspnetuserRoles table):示例代码如下(Authors 和 Books 表包含多对多关系,BookAuthor 是连接表,类似于 aspnetuserRoles 表):
var result = _dbcontext.Authors
.Include(c => c.BookAuthor)
.ThenInclude(c => c.Book)
.SelectMany(c => c.BookAuthor.Select(d => new BookAuthorViewModel()
{
Id = d.Author.Id,
AuthorName = d.Author.AuthorName,
BookName = d.Book.BookName,
ISBN = d.Book.ISBN
})).ToList();
The Models as below:型号如下:
public class Book
{
[Key]
public int Id { get; set; }
public string BookName { get; set; }
public string ISBN { get; set; }
public IList<BookAuthor> BookAuthor { get; set; }
}
public class Author
{
[Key]
public int Id { get; set; }
public string AuthorName { get; set; }
public IList<BookAuthor> BookAuthor { get; set; }
}
public class BookAuthor
{
public int BookId { get; set; }
public Book Book { get; set; }
public int AuthorId { get; set; }
public Author Author { get; set; }
}
Create a ViewModel to display the query result.创建一个 ViewModel 来显示查询结果。
public class BookAuthorViewModel
{
[Key]
public int Id { get; set; }
public string BookName { get; set; }
public string AuthorName { get; set; }
public string ISBN { get; set; }
}
Then, the output like this:然后,输出如下:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.