lightgunsuicide
lightgunsuicide

Reputation: 11

Mongodriver (c#/.netcore 2.0) able to return single documents but not whole collections as a list

For a single document, I am able to return and deserialise a value as below:

 public IPlayer FindById(BsonObjectId id)
        {
            var filter = new BsonDocument("_id", id);
            var player = _collection.Find(filter).Single();
            var deserialisedPlayer = BsonSerializer.Deserialize<PlayerDto>(player);
            return deserialisedPlayer;
        }

Previously when I've wanted to return and deserialise an entire collection of documents as a list, I've been able to do so as:

 public async Task<string> GetRiskLevelAggregatedTotal(int int1, string string1, string string2)
        {
            var builder = Builders<BsonDocument>.Filter;
            var filter = builder.Eq("LastSnapshotData.String1", string1) &
                         builder.Eq("LastSnapshotData."+ string2 + ".Example.Id", int1);
            var result = await _patientCollection.Find(filter).ToListAsync();


            return result.Count.ToString();
        }

However when attempting something similar in a .netcore 2.0 project:

 public List<IPlayer> FindAll()
        {
            var builder = Builders<BsonDocument>.Filter;
            var filter = builder.Eq("name", "Lorem Ipsum");
            var allPlayers =  _collection.Find(filter).ToList();

            return allPlayers;
        }

I get the following: System.Private.Corelib issue

Thinking maybe the toList is now implicit when returning multiple documents I tried omitting it and simply using the return value of the find, but this just returns a IFluentFind definition. Is there something missing from my framework set up?

Thanks in advance

Upvotes: 1

Views: 99

Answers (1)

pieperu
pieperu

Reputation: 2762

Instead of deserializing the objects in a separate operation, why not declare your collection with your type, so you might have something like:

IMongoCollection<PlayerDTO> _collection

And then it's just a case of using linq to query it, the deserialization is done for you

See this post for more information on basic use of Find in C#

MongoDB and C# Find()

Upvotes: 1

Related Questions