[英]MongoDB C# 2.1 ReplaceOneAsync not working for repository pattern
我正在尝试为mongodb实现异步存储库模式。 这是我的代码:
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 });
}
}
和控制台应用程序只是调用逻辑:
class Program
{
static void Main(string[] args)
{
var userRepo = new MongoDbRepository<User>();
userRepo.Save(new User
{
FirstName = "fn",
LastName = "ln"
}).Wait();
Console.ReadKey();
}
}
在这行代码中:
return await _collection.ReplaceOneAsync(w => w.Id == doc.Id, doc, new UpdateOptions { IsUpsert = true });
我收到一个错误:
不支持Convert([document])。Id。
如果我要像这样更改代码,则可以正常工作:
private IMongoCollection<EntityBase> _collection;
private void GetCollection()
{
_collection = _database.GetCollection<EntityBase>(typeof(EntityBase).Name);
}
但是我真的需要使用T代替BaseMongoClass ...为什么会出现此错误以及如何解决该错误的任何想法? 非常感谢!
刚刚解决了同样的问题。 摆脱==
,由于某种原因,新的mongo驱动程序不喜欢它。 我用.Equals()
更改
return await _collection.ReplaceOneAsync(w => w.Id == doc.Id,
doc, new UpdateOptions { IsUpsert = true });
至
return await _collection.ReplaceOneAsync(w => w.Id.Equals(doc.Id),
doc, new UpdateOptions { IsUpsert = true });
如果您使用接口时也会发现此问题,
解决方案代替id使用_id
var filter = Builders<IVideo>.Filter.Eq("_id", doc.Id);
await _collection.ReplaceOneAsync(filter , doc, new UpdateOptions { IsUpsert = true });
对于MongoDB驱动程序2.4.4,在过滤器上使用“等于”比较(不了解“ _id”):
var filter = Builders<T>.Filter.Eq(c => c.Id, doc.Id);
await collection.ReplaceOneAsync(filter, doc, new UpdateOptions { IsUpsert = true });
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.