No matching creator found
For people using LINQ queries like myself, you could also consider using coalesce expression (aka ??
) in Select
to avoid having to create unnecessary concrete types.
MongoDB.Driver 2.11.2 was used when writing below examples
Consider this query:
var query = Collection
.Where(x => filter.Inject())
.Select(x => new
{
Title = x.Title // Some old entities do not have Title
});
The query will be translated to $project
like:
aggregate([{ "$project" : { "Title" : "$title" } }])
When some items do not have $title
, the result cannot be mapped to anonymous type for the reason as per @r-j has stated, and the exception raises:
No matching creator found.
If apply coalesce against x.Title
:
new
{
Title = x.Title ?? null
}
Then the query will be translated to:
aggregate([{ "$project" : { "Title" : { "$ifNull" : ["$title", null] } } }])
In which way a Title
is guaranteed in the result.
The downside of this approach is the C# expression does look a bit confusing if look from C#'s perspective. If you enable nullable reference type and the Title
property is not null in C#, you will see a warning/hint saying the left operand is never null.
I encountered this error today. Similar to the person asking the question, I had an anonymous type being populated from a mongo query.
The error seems to happen when the element you're fetching does not exist in database. In this case, mongo driver seems to get confused about what "type" the resulting anonymous type should be generated as.
I changed my anonymous type to a concrete type (by declaring a class for it) and that fixed the error.