0

I am using MongoDB for my database and I am using ASP.NET Core for my api. I am trying to convert my Items object to a ItemsDTO (Data Transfer Object), because I don't want to return the Id. However, when I use

_items.AsQueryable()
.Where(item => item.Game.Contains("Games/1"))
.Select(item => ItemToDTO(item))
.ToList();

It gives back a System.NotSupportedException: 'ItemToDTO of type Project.Services.ItemService is not supported in the expression tree ItemToDTO({document}).' By the way ItemToDTO looks like this:

private static ItemDTO ItemToDTO(Item item)
        {
            return new ItemDTO
            {
                Name = item.Name,
                Type = item.Type,
                Price = item.Price,
                Game = item.Game,
                CostToSell = item.CostToSell,
                Description = item.Description
            };
        }

So I am confused on why this doesn't work because before I was using a SQL Server Database and normal Linq that looked like this:

_context.Items
.Where(item => item.Game.Contains("Games/1"))
.Select(item => ItemToDTO(item))
.ToList(),

and it worked the data that I wanted. I know that when using the MongoDB.Driver I am using their Linq and Queryable objects. Just wondering why I am getting the error above.

1 Answer 1

1

It is typical mistake when working with LINQ. Translator can not look into ItemToDTO function body and will materialize whole item and then call ItemToDTO to correct result. Probably it is not a way for MongoDb and bad way for relational databases.

So I propose rewrite your function and create extension:

public static IQueryable<ItemDTO> ItemToDTO(this IQueryable<Item> items)
{
   return items.Select(item => new ItemDTO
   {
       Name = item.Name,
       Type = item.Type,
       Price = item.Price,
       Game = item.Game,
       CostToSell = item.CostToSell,
       Description = item.Description
   });
}

Then your query should work fine:

_context.Items
   .Where(item => item.Game.Contains("Games/1"))
   .ItemToDTO()
   .ToList()
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.