ASP MVC5 LINQ 多选与列表

本文关键字:列表 MVC5 LINQ ASP | 更新日期: 2023-09-27 18:33:48

我正在编写一个简单的社区插件,现在我想改进我的数据库查询,但遇到了阻塞问题:

这是查询:

TRDCommunityViewModel community = await _db.Communities
  .Select(c => new TRDCommunityViewModel
   {
    Id = c.Id,
    CommunityId = c.Guid,
    Created = c.Created,
    Description = c.Description,
    IAmAdmin = (c.Admins.FirstOrDefault(k => k.Id == userId) != null),
    Members = c.Members.Select(a => new List<TRDIdenityViewModel>()
      {
        // member vars of TRDIdenityViewModel arn't accessible
        // ???
      }),
    Posts = c.Posts.Select(a => new List<TRDIdenityViewModel>()
      {
        //member vars of TRDIdenityViewModel arn't accessible
      })
        // and so on
    })
   .FirstOrDefaultAsync(k => k.Id == Id);

我的问题是...如何查询相关列表?成员和帖子是 ICollection

谢谢你的帮助。

ASP MVC5 LINQ 多选与列表

您不需要在 Select 中实例化列表,这应该可以工作:

TRDCommunityViewModel community = await _db.Communities
  .Select(c => new TRDCommunityViewModel
   {
    Id = c.Id,
    CommunityId = c.Guid,
    Created = c.Created,
    Description = c.Description,
    IAmAdmin = (c.Admins.FirstOrDefault(k => k.Id == userId) != null),
    Members = c.Members.Select(a => new TRDIdenityViewModel()
      {
        // do your assignments here...
      }),
    Posts = c.Posts.Select(a => new TRDIdenityViewModel()
      {
        //do your assignments here...
      })
        // and so on
    })
   .FirstOrDefaultAsync(k => k.Id == Id);

如果需要,您可以通过在选择后调用ToList()来实现,例如:

    Posts = c.Posts.Select(a => new TRDIdenityViewModel()
      {
        //do your assignments here...
      }).ToList()