我在数据库中使用MongoDB,在我的api中使用ASP.NET Core。我想将我的Items对象转换为ItemsDTO(数据传输对象),因为我不想返回ID。但是,当我使用
_items.AsQueryable()
.Where(item => item.Game.Contains("Games/1"))
.Select(item => ItemToDTO(item))
.ToList();
它返回System.NotSupportedException:“表达式树ItemToDTO({document})中不支持类型为Project.Services.ItemService的ItemToDTO。” 顺便说一下,ItemToDTO看起来像这样:
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
};
}
因此,我对为什么这种方法不起作用感到困惑,因为在我使用SQL Server数据库和普通的Linq之前,它看起来像这样:
_context.Items
.Where(item => item.Game.Contains("Games/1"))
.Select(item => ItemToDTO(item))
.ToList(),
它可以处理我想要的数据。我知道在使用MongoDB.Driver时,我正在使用它们的Linq和Queryable对象。只是想知道为什么我得到上面的错误。
使用LINQ时,这是典型的错误。转换器不能查看ItemToDTO
函数体,而是 会整体实现item
,然后调用ItemToDTO
以纠正结果。可能这不是MongoDb的方法,也不是关系数据库的坏方法。
因此,我建议重写你的函数并创建扩展:
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
});
}
然后你的查询应该可以正常工作:
_context.Items
.Where(item => item.Game.Contains("Games/1"))
.ItemToDTO()
.ToList()
这个工作非常感谢你