Warm tip: This article is reproduced from serverfault.com, please click

c#-使用MongoDB.Driver.Linq时获取System.NotSupportedException

(c# - Getting a System.NotSupportedException when using MongoDB.Driver.Linq)

发布于 2020-11-28 19:58:47

我在数据库中使用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对象。只是想知道为什么我得到上面的错误。

Questioner
Christian Moore
Viewed
0
Svyatoslav Danyliv 2020-11-29 17:23:39

使用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()