I'm trying to implement async repository pattern for mongodb. This is my code:
public class EntityBase
{
[BsonId]
public ObjectId Id { get; set; }
}
public class User : EntityBase
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
public class MongoDbRepository<T> where T : EntityBase
{
private IMongoDatabase _database;
private IMongoCollection<T> _collection;
public MongoDbRepository()
{
GetDatabase();
GetCollection();
}
private void GetDatabase()
{
var client = new MongoClient("mongodb://localhost/");
_database = client.GetDatabase("LocalTest");
}
private void GetCollection()
{
_collection = _database.GetCollection<T>(typeof(T).Name);
}
public async Task<ReplaceOneResult> Save(T doc)
{
return await _collection.ReplaceOneAsync(w => w.Id == doc.Id, doc, new UpdateOptions { IsUpsert = true });
}
}
And console application which just calling the logic:
class Program
{
static void Main(string[] args)
{
var userRepo = new MongoDbRepository<User>();
userRepo.Save(new User
{
FirstName = "fn",
LastName = "ln"
}).Wait();
Console.ReadKey();
}
}
In this line of code:
return await _collection.ReplaceOneAsync(w => w.Id == doc.Id, doc, new UpdateOptions { IsUpsert = true });
I'm getting an error:
Convert([document]).Id is not supported.
If I'm changing the code like this, it's working:
private IMongoCollection<EntityBase> _collection;
private void GetCollection()
{
_collection = _database.GetCollection<EntityBase>(typeof(EntityBase).Name);
}
But I really need to use T instead of BaseMongoClass... Any ideas why this error occurs and how can I fix it? Thanks a lot!
Just solved the same problem. Get rid of the ==
, for some reason the new mongo driver doesn't like it. I used .Equals()
Change
return await _collection.ReplaceOneAsync(w => w.Id == doc.Id,
doc, new UpdateOptions { IsUpsert = true });
To
return await _collection.ReplaceOneAsync(w => w.Id.Equals(doc.Id),
doc, new UpdateOptions { IsUpsert = true });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With