【问题标题】:ASP NET Core - Use OData with mongoDB - Fails serializerASP NET Core - 将 OData 与 mongoDB 一起使用 - 序列化程序失败
【发布时间】:2020-07-03 20:09:35
【问题描述】:

我正在尝试将 OData 集成到 ASP NET Core 应用程序中。 特殊性是我有一个 Mongo DB,我使用 Mongo DB 驱动程序将我的请求设置为IQueryable;我已经简化了下面的代码,似乎序列化程序 mongo 失败了

[HttpGet]
[EnableQuery]
public async Task<IActionResult> Index(ODataQueryOptions<Policy> queryOptions)
{
    var client = new MongoClient("mongodb://127.0.0.1:27017");
    var collection = client.GetDatabase("policy-server").GetCollection<Policy>("policy");
    var policies = collection.AsQueryable();
    var query = queryOptions.ApplyTo(policies);
    var s = query.ToString(); // error in toString()
    return Ok(s); 
}

调用他的 URL [https://localhost:44355/api/policies?$select=isEnabled][1] 时出现以下错误

ArgumentException: 序列化程序的值类型是 Microsoft.AspNet.OData.Query.Expressions.PropertyContainer+NamedProperty1[[System.Nullable1[[System.Boolean, System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken =7cec85d7bea7798e]],System.Private.CoreLib,版本=4.0.0.0,Culture=neutral,PublicKeyToken=7cec85d7bea7798e]] 并且与成员类型 Microsoft.AspNet.OData.Query.Expressions.PropertyContainer 不匹配。 (参数“序列化器”) BsonMemberMap.cs 中的 MongoDB.Bson.Serialization.BsonMemberMap.SetSerializer(IBsonSerializer 序列化器),第 480 行

有人可以混合使用 OData 和 MongoDB 驱动程序吗?

谢谢

【问题讨论】:

  • 您找到解决问题的方法了吗?在这里面对完全相同的:(
  • 算了。我推出了自己的 OData 解析器,并以一种非搞砸的方式生成了我的表达式(与 .net 不同),它工作得很好;)
  • 你能在没有 OData 的情况下检查这个查询吗?这看起来很简单,如果它在没有 odata 的情况下导致此问题,我可以提供帮助
  • @dododo 使用 select 时出现问题,而不是 orderby 或 filter
  • 你在使用 IIF 语句吗?

标签: c# asp.net-core odata mongodb-.net-driver


【解决方案1】:

query 的类型为 IQueryable

查看示例

public PageResult<Product> Get(ODataQueryOptions<Product> options)
{
ODataQuerySettings settings = new ODataQuerySettings()
{
    PageSize = 5
};

IQueryable results = options.ApplyTo(_products.AsQueryable(), settings);

return new PageResult<Product>(
    results as IEnumerable<Product>, 
    Request.GetNextPageLink(), 
    Request.GetInlineCount());
}

https://docs.microsoft.com/en-us/aspnet/web-api/overview/odata-support-in-aspnet-web-api/supporting-odata-query-options

您正在对 IEnumerable 集合 (https://docs.microsoft.com/en-us/dotnet/api/system.linq.iqueryable?view=net-5.0) 执行 ToString(),而 forEach 将执行例如(甚至类似 String.Join(",",query.Select(r =&gt; r.SomeField)) 之类的操作)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-07-17
    • 2021-03-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多