简体   繁体   中英

How to cast mongo collection to interface C#

I have a repository with signature:

public Task<IList<IFoo>> GetList()
{

}

How do I cast mongoDb collection to this interface? (MongoDb Driver 2.0)

public Task<IList<IFoo>> GetList()
{
    Task<List<Foo>> foo = this.database.GetCollection<Foo>("Foo").Find(e => true).ToListAsync();

    return foo ; // ?? somehow cast Task<List<Foo>> to Task<IList<IFoo>>
}

also, this code bothers me

collection.Find(e => true).ToListAsync()

Is there a better way to get all documents in collection?

There are 2 questions here.

  1. How do you cast Task<List<Foo>> to Task<IList<IFoo>> ?

You can't, because Task isn't covariant in .Net. You can unwrap the result with await but it still wouldn't work as you can't cast List<Foo> into IList<IFoo> .

What you can do is create a new List<IFoo> and cast all the items when you move them over:

public async Task<IList<IFoo>> GetList()
{
    List<Foo> results = await database.GetCollection<Foo>("Foo").Find(_ => true).ToListAsync();
    return results.Cast<IFoo>().ToList();
}
  1. Is there a better way to get all documents in collection?

Not right now. You can pass in an empty filter document ( new BsonDocument() ), but I don't think it's any better. In the next version (v2.1) of the driver they've added an empty filter so you can do this:

await database.GetCollection<Foo>("Foo").Find(Builders<Foo>.Filter.Empty)

Here it says you have to call FindAsync with an empty filter to return all the documents in a collection:

To return all documents in a collection, call the FindAsync method with an empty filter document

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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