2017-10-12 62 views
0

在C#中使用LINQ to編寫複雜的查詢,可以編寫代碼如:蒙戈C#驅動程序:如何使用本機API

public static class MyEntityExtensions { 
    public static IQueryable<MyEntity> ByCodeSystem(IQueryable<MyEntity> items, int codeSystemId) { 
     return items.Where(o => o.CodeSystemId == codeSystemId); 
    } 

    public static IQueryable<MyEntity> NotDeleted(IQueryable<MyEntity> items) { 
     return items.Where(o => !o.Deleted); 
    } 
} 

,然後用它是這樣的:

DbSet<MyEntity> allMyEntities = myDbContext.MyEntities; 
var myFilteredEntities = allMyEntities 
    .ByCodeSystem(42) 
    .NotDeleted() 
    .Select(e => new { Id = e.Id, Name: e.Name }) 
    .ToArray(); // Materialize only the filtered ones and project only the needed data 

哪有在查詢MongoDb和它的本地API時會這樣做嗎? 我知道通過使用IMongoCollection.AsQueryable()可以完全像這樣使用集合,但某些mongo運算符更直接由本地API映射(即:Builders.Filter。,Builders.Sort。ecc)。

回答

3

你可以做同樣的擴展方法來擴展蒙戈過濾器製造商,爲您的LINQ的例子,我們可以有:

public static class MyModelFilterDefinitionBuilderExtentions 
{ 
    public static FilterDefinition<MyModel> IsNotDeleted(this FilterDefinitionBuilder<MyModel> filter) 
    { 
     return filter.Eq(x => x.Deleted, false); 
    } 

    public static FilterDefinition<MyModel> ByCodeSystem(this FilterDefinitionBuilder<MyModel> filter, int codeSystemId) 
    { 
     return filter.Eq(x => x.CodeSystemId, codeSystemId); 
    } 
} 

我們可以使用

mongoCollection.Find(Builders<MyModel>.Filter.IsNotDeleted()); 

然後應用它還是應用多個

var filter = Builders<MyModel>.Filter.IsNotDeleted() & Builders<MyModel>.Filter.ByCodeSystem(10); 
mongoCollection.Find(filter); 
+1

+1的答案。我想補充一點,有Builders .Filter.And和Builders .Filter.Or用於使用驅動程序的級聯過濾器。 – BOR4

+0

似乎是目前唯一的方法。在一個不太詳細的問題出現之前,我會接受答案。順便說一句,不知道按位運算符重載鏈接在布爾表達式過濾器...很好的接觸 – Etchelon