ASP MVC5 LINQ多选用列表

时间:2014-12-10 17:57:12

标签: c# jquery asp.net-mvc linq

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

这是查询:

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);

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

帮助你。

1 个答案:

答案 0 :(得分:1)

您不需要在Select中实例化List,这应该有效:

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()