FindOneAndUpdateAsync C# usage with linq expression

Hi,

I try to use FindOneAndUpdate in C# with linq expression but I don’t find how to do it.

public class Task4
{
public ObjectId _id;
public int state = 0;
public DateTime start;
}

var t4 = await collection.FindOneAndUpdateAsync(
_ => _._id == id && .state == searchState, <= Problem here
Builders.Update
.Set(
=> .state, state)
.CurrentDate(
=> _.start, UpdateDefinitionCurrentDateType.Date),
new FindOneAndUpdateOptions<Task4, Task4>() <= or here ?
{
ReturnDocument = ReturnDocument.After
},
cancellationToken: cancel
);

But it’s impossible and I don’t find how to fix that.
I get the error

error CS0121: The call is ambiguous between the following methods or properties: ‘IMongoCollectionExtensions.FindOneAndUpdateAsync(IMongoCollection, Expression<Func<TDocument, bool>>, UpdateDefinition, FindOneAndUpdateOptions<TDocument, TDocument>, CancellationToken)’ and ‘IMongoCollectionExtensions.FindOneAndUpdateAsync<TDocument, TProjection>(IMongoCollection, Expression<Func<TDocument, bool>>, UpdateDefinition, FindOneAndUpdateOptions<TDocument, TProjection>, CancellationToken)’

If you want the full project get it here

Thanks for your help.

Hi, @Remi_Thomas,

Welcome back to the MongoDB Community Forums. I understand that you’re receiving an ambiguity between two FindOneAndUpdateAsync overloads based on the compiler warning. The problem is that there are two similar overloads, which the compiler cannot differentiate between. These two overloads are:

Task<TDocument> FindOneAndUpdateAsync<TDocument>( ... params ... )
Task<TProjection> FindOneAndUpdateAsync<TDocument, TProjection>( ... params ... )

Often the C# compiler can infer the type arguments based on the method parameters, but in this case the method parameters are identical. To resolve this ambiguity, you must explicitly specify the type parameter:

var t4 = await collection.FindOneAndUpdateAsync<Task4>(
_ => _._id == id && .state == searchState,
... additional params ...

Hope this helps.

Sincerely,
James

1 Like