C# Asp.Net.Net 5 Lambda LINQ获取与Asp.Net标识中的用户帐户关联的角色名称
我正在使用Asp.Net.Net5和实体框架5 我有三张桌子C# Asp.Net.Net 5 Lambda LINQ获取与Asp.Net标识中的用户帐户关联的角色名称,c#,asp.net,linq,asp.net-core,.net-5,C#,Asp.net,Linq,Asp.net Core,.net 5,我正在使用Asp.Net.Net5和实体框架5 我有三张桌子 aspnetuser aspnetroles aspnetuserRoles=链接表 我当前的LINQ代码返回来自用户和用户角色的所有数据,但不返回来自aspnetrole表的任何数据。我希望它返回用户和他们当前分配的角色,以便我可以看到他们是管理员还是标准 public async Task<IList<User>> GetAllEnabledAccounts() { var
public async Task<IList<User>> GetAllEnabledAccounts()
{
var users = await _context.Users
.Where(u => u.IsEnabled == true)
.Include(r => r.UserRoles)
.ToListAsync();
return users;
}
aspnetRoles
id | name
----------
1 | admin
2 | standard
aspnetuserRoles
userId | roleId
----------------
1 | 1
2 | 2
当查询时,它应该返回用户Jim,显示他是管理员,Harry,显示他是标准帐户。如何键入LINQ查询以正确输出信息?根据您的代码,我假设已配置了aspnetuser和aspnetRoles,对吗?如果是这种情况,您可以参考以下示例,并使用包含,然后包含和选择多个方法来查询相关实体 示例代码如下(Authors和Books表包含多对多关系,BookAuthor是联接表,与aspnetuserRoles表类似): 模型如下所示:
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; }
}
然后,输出如下所示:
根据您的代码,我想aspnetuser和aspnetRoles已经配置好了,对吗?如果是这种情况,您可以参考以下示例,并使用包含,然后包含和选择多个方法来查询相关实体 示例代码如下(Authors和Books表包含多对多关系,BookAuthor是联接表,与aspnetuserRoles表类似): 模型如下所示:
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; }
}
然后,输出如下所示:
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; }
}
public class BookAuthorViewModel
{
[Key]
public int Id { get; set; }
public string BookName { get; set; }
public string AuthorName { get; set; }
public string ISBN { get; set; }
}