I'm using MongoDB in my MVC project and am creating a utility function that I could use to delete records in database.
I am using :
- mongo db extension for C#
- C#(.net 4.6.1)
To method is passed record what I want to delete. I filter all recordings in DB by id of passed recording what I want to delete. Finding it I want to delete it. my method
public virtual async Task<T> Delete(EmailBlastDocument input)
{
var filter = Builders<T>.Filter.Eq(p => p.Id, input.Id);
var collection = DocumentContext.DocumentClient.GetDatabase(DatabaseName).GetCollection<T>(CollectionName);
return await collection.DeleteOneAsync(filter);
}
But it highlights error on compile time
Cannot implicitly convert type 'MongoDB.Driver.DeleteResult' to 'T'
How do I fix this function to properly return the result of delete record to the caller? And how to properly delete record in mongoDB
I have create Update method what was took as example
public virtual async Task<T> Update(T input)
{
var collection = DocumentContext.DocumentClient.GetDatabase(DatabaseName).GetCollection<T>(CollectionName);
try
{
await collection.ReplaceOneAsync(a => a.Id == input.Id, input);
}
catch (MongoWriteException ex)
{
switch (ex.WriteError.Category)
{
case ServerErrorCategory.ExecutionTimeout:
throw new TimeoutException();
default:
throw new CirrusDocumentGeneralException();
}
}
return input;
}
CodePudding user response:
I'm still not 100% clear what you're trying to do here. I'm also not sure why the method accepts a EmailBlastDocument
and not a T
. I'm assuming it should be T
.
If you want to change it to work similarly to Update
you could change it to be like this:
public virtual async Task<T> Delete(T input)
{
var filter = Builders<T>.Filter.Eq(p => p.Id, input.Id);
var collection = DocumentContext.DocumentClient.GetDatabase(DatabaseName).GetCollection<T>(CollectionName);
await collection.DeleteOneAsync(filter); // do the delete
return input; // return the input
}
This will return the input document as a result of the delete. Note that the input
document could be different to the last value in the database.
If you want to return the absolute latest version of the document, you can use FindOneAndDeleteAsync
:
public virtual async Task<T> Delete(T input)
{
var filter = Builders<T>.Filter.Eq(p => p.Id, input.Id);
var collection = DocumentContext.DocumentClient.GetDatabase(DatabaseName).GetCollection<T>(CollectionName);
return await collection.FindOneAndDeleteAsync(filter);
}
This will return the document as it was inn the database just before it got deleted.