【问题标题】:Casting an object not supported in .NET MongoDB C# Driver.NET MongoDB C# 驱动程序不支持强制转换对象
【发布时间】:2014-01-23 02:42:38
【问题描述】:

我在 MongoDB 中存储文档,由以下类表示:

public class Entity
{
    public string Id;
    public string Name;
    public List<EntityAttribute> Attributes = new List<EntityAttribute>();
}

public class EntityAttribute
{
    public string Key;
    public object Value;
    public string DataType;
}



“EntityAttribute”上的“Value”对象显然可以是任何类型的对象(字符串、int、float等),这就是意图。

当我的应用尝试使用关系运算符(例如“”)执行查询时,它会将“EntityAttribute.Value”对象转换为适当的类型(以便使用关系运算符)。下面是一个例子:

var results = entities.AsQueryable<Entity>()
                .Where(x => x.Type == "dogs" && 
                    x.Attributes.Any(a => a.Key == "age" && (int)a.Value > 5)).ToList();


这会产生以下异常:

Unsupported where clause: ((Int32)a.Value > 5).


我正在使用 MongoDB CSharp Linq 驱动程序 (http://docs.mongodb.org/ecosystem/tutorial/use-linq-queries-with-csharp-driver/)。我的假设是不支持强制转换。是这样吗?

作为比较,这种相同类型的语法(linq 查询)在 RavenDB 的 LINQ 驱动程序中确实有效,即:

var results = session.Query<Entity>()
                        .Where(x => x.Type == "dogs")
                        .Intersect()
                        .Where(x => x.Attributes.Any(a => a.Key == "age" && (int)a.Value > 5)).ToList();


有没有什么方法可以通过 LINQ 使用 MongoDB CSharp LINQ 驱动程序来完成此任务?

我可以使用 Query.EQ 让所有必需的查询工作, Query.GT 和 Query.LT,但如果可能的话,我宁愿使用 LINQ。

【问题讨论】:

  • 我认为问题可能是您的查询无法转换为 MongoDB 查询。您是否检查过它是否在没有演员表(int)的情况下工作?您可以找到比较between different types,但您可以通过按数据类型添加新过滤器来解决此问题(您的 EntityAttribute 类中已经有该字段)

标签: c# .net linq mongodb


【解决方案1】:

C# 驱动程序当前不支持这种形式的 LINQ 查询(将对象类型的字段向下转换为更具体的类以进行比较),这是正确的。

我创建了一个请求此功能的 JIRA 票证。见:

https://jira.mongodb.org/browse/CSHARP-900

【讨论】:

  • 是否可以在 ExpandoObjects 上运行查询?他们肯定需要演员吗?
猜你喜欢
  • 2019-05-13
  • 1970-01-01
  • 1970-01-01
  • 2022-07-21
  • 1970-01-01
  • 2011-04-11
  • 2020-03-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多