我在 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”对象显然可以是任何类型的对象(string、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获得所有需要的查询strong>、Query.GT 和 Query.LT,但如果可能我宁愿使用 LINQ。
最佳答案
您是正确的,C# 驱动程序目前不支持这种形式的 LINQ 查询(将对象类型的字段向下转换为更具体的类以便进行比较)。
我已经创建了一个请求此功能的 JIRA 票证。见:
关于c# - .NET MongoDB C# 驱动程序不支持转换对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21298311/