根据嵌套数组中的条件选择一个对象(LINQ,MongoDB)

时间:2018-03-13 05:07:25

标签: c# asp.net mongodb model-view-controller asp.net-core

{
"Id": 1234,
"CommentType": "project",
"EntityReferenceId": "1345-154-154",
"Members": [{
    "MemberId": "1354",
    "Name": "a",
    "Email": "cdc@df.com"
}],
"Threads": [{
        "Id": "233",
        "UserReferenceId": "32343",
        "UserName": "433434",
        "CommentByUserType": "Agent",
        "Content": "dfdfdsfs sfdf sdf",
        "PostedDate": "0001-01-01T00:00:00",
        "Active": true,
        "Attachment": [{
            "AttachmentName": "ad",
            "AttachmentUrl": "http://fdf.jpg"
        }]
    },
    {
        "Id": "233",
        "UserReferenceId": "32343",
        "UserName": "433434",
        "CommentByUserType": "Agent",
        "Content": "dfdfdsfs sfdf sdf",
        "PostedDate": "0001-01-01T00:00:00",
        "Active": false,
        "Attachment": [{
            "AttachmentName": "ad",
            "AttachmentUrl": "http://fdf.jpg"
        }]
    }]
}

我正在使用MongoDb来linq, 这是我的注释“对象格式。每个项目都有一个注释对象。每个注释对象包含一个”线程“列表(你可以看到上面的例子)。我想用所有线程加载”注释“对象有效(“有效”:真实)

var result = _context.Comments
                     .AsQueryable()
                     .Where(x => x.EntityReferenceId == EntityReferenceId &&
                                 x.CommentType == Type && 
                                 x.Threads.Any(z=>z.Active==true))
                     .FirstOrDefault();

我使用了这个查询,但如果任何线程的“Active”值为true,它会加载所有线程。

 x.Threads.Any(z=>z.Active==true) 

只返回bool值。我需要一个解决方案

1 个答案:

答案 0 :(得分:2)

您可以使用x.Threads.Any(z=>z.Active==true) where条件。 或者您将判断Threads集合包含Active==true数据。

你可以这样做一个简单的方法。

var result = _context.Comments
         .AsQueryable()
         .Where(x => x.EntityReferenceId == EntityReferenceId &&
                     x.CommentType == Type)
         .FirstOrDefault();

if (result!=null)
{
    result1.Threads = result1.Threads.Where(z => z.Active == true);
}

使用select方法

var result = _context.Comments
                     .AsQueryable()
                     .Where(x => x.EntityReferenceId == EntityReferenceId &&
                                 x.CommentType == Type)
                     .Select(o => new Comment{
                        Id = o.Id,
                        Members = o.Members,
                        EntityReferenceId = o.EntityReferenceId,
                        CommentType = o.CommentType,
                        Threads = o.Threads.Where(z => z.Active == true)
                     })
                     .FirstOrDefault();