繁体   English   中英

C# MongoDB 加入集合并包含过滤器

[英]C# MongoDB join collections and include filters

开始使用 MongoDB.Driver 在我的 .net 核心应用程序中使用 MongoDB。 我需要找到一种方法来加入集合并包含过滤器。

寻找如何加入这是我发现的 -

            var query = from c in collection1.AsQueryable()
                        join m in collection2.AsQueryable() on
                 c.ClassTwoId equals m.Id into j
                        select new { c, j };

寻找如何过滤这是我发现的 -

            //filters
            FilterDefinitionBuilder<PortalUser> builder = Builders<PortalUser>.Filter;
            List<FilterDefinition<PortalUser>> filters = new List<FilterDefinition<PortalUser>>();
            filters.Add(builder.Eq(PortalUser => PortalUser.IsActive, true));

            var result = portalUserCollection.FindAsync<PortalUser>(builder.And(filters));

找不到任何方法来组合上面的例子......我发现过滤 IQueryable 的唯一方法是在 IQueryable 中添加一个 where 语句,但是由于过滤器是动态的并且决定运行时,这意味着我必须这样做很多 if/else 并每次都重建 IQueryable 听起来很疯狂......

有人知道解决方法吗?

非常感谢。

使用 Where 子句。

var query = from c in collection1.AsQueryable().Where(x => x.Name == "Test")
            join m in collection2.AsQueryable() on
            c.ClassTwoId equals m.Id into j
            select new { c, j };

通过添加 nuget 包 System.Linq.Dynamic 使其动态化

using System.Linq.Dynamic;
....
var query = from c in collection1.AsQueryable().Where("Age == 123")
            join m in collection2.AsQueryable() on 
            c.ClassTwoId  equals m.Id into j
            select new { c, j };

有关动态查询的更多信息,请参阅 System.Linq.Dynamic(参数等)文档

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM