Reputation: 23
When building the query, I can use the Select method and create a new model where I can select whatever i need. for example:
var queryOptions = new FeedOptions { MaxItemCount = -1, PartitionKey = new PartitionKey("test") };
var queryResponse = DocumentClient.CreateDocumentQuery<User>(DocumentCollectionUrl, queryOptions)
.Where(x => x.Id == id)
.Select(x => new UserViewModel
{
Name = x.Name
})
.AsDocumentQuery();
this will create a query that selects only the Name, and it works as it should.
Now, if i create an extension method, and call it in the select method, like this:
var queryResponse = DocumentClient.CreateDocumentQuery<User>(DocumentCollectionUrl, queryOptions)
.Where(x => x.Id == id)
.Select(x => x.ToShortModel())
.AsDocumentQuery();
I get the following error: {"Method 'ToShortModel' is not supported., Windows/10.0.17763 documentdb-netcore-sdk/2.4.0"}
Do I need to create a new model if I want to select only a few properties? Or should i just go with the first example?
the extension method ToShortModel:
public static UserViewModel ToShortModel(this User entity)
{
return new UserViewModel
{
Name = entity.Name
};
}
Thank you in advance.
Upvotes: 0
Views: 446
Reputation: 987
I believe this happens because of projection. When the SDK see the expression in the first SELECT, it is able to create a query that looks like this:
SELECT c.name
FROM collections c
WHERE c.id = id
but when you use the extension method inside your select, the SDK is no longer able to do the query since ToShortModel does not exist. Remember that the SDK tries to convert the linq expression to a query that is actually executed in CosmosDb.
A solution could be to create an extension that include the all select. Something like this:
public static IQueryable<UserViewModel> SelectName<TEntity>(this IQueryable<TEntity> queryable)
{
return queryable.Select(x => new UserViewModel
{
Name = x.Name
});
}
You would use it like this:
var queryResponse = DocumentClient.CreateDocumentQuery<User>(DocumentCollectionUrl, queryOptions)
.Where(x => x.Id == id)
.SelectName()
.AsDocumentQuery();
Upvotes: 1