Alexander Selishchev
Alexander Selishchev

Reputation: 1287

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?

Upvotes: 4

Views: 2196

Answers (2)

i3arnon
i3arnon

Reputation: 116596

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)

Upvotes: 4

goodolddays
goodolddays

Reputation: 2683

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

Upvotes: 1

Related Questions