c# - MongoDB Unable to determine the serialization information for the expression 错误

标签 c# .net mongodb mongodb-.net-driver

我的数据结构如下

public enum ParamType
{
    Integer=1,
    String=2,
    Boolean=3,
    Double=4
}

public class Gateway
{
    public int _id { get; set; }
    public string SerialNumber { get; set; }
    public List<Device> Devices { get; set; }
}

public class Device
{        
    public string DeviceName { get; set; }
    public List<Parameter> Parameters { get; set; }
}

public class Parameter
{
    public string ParamName { get; set; }
    public ParamType ParamType { get; set; }
    public string Value { get; set; }
}

我在一个MongoDB数据库中填入了10个Gateway的文档对象。 现在我想查询所有那些包含一个设备的网关,该设备的参数为 ParamName 作为“目标温度”并且其 Value > 15。

我创建了以下查询

var parameterQuery = Query.And(Query<Parameter>.EQ(p => p.ParamName, "Target Temperature"), Query<Parameter>.GT(p => int.Parse(p.Value), 15));

var deviceQuery = Query<Device>.ElemMatch(d => d.Parameters, builder => parameterQuery);

var finalQuery = Query<Gateway>.ElemMatch(g => g.Devices, builder => deviceQuery);

但是当我运行它时,它给出了一个异常

Unable to determine the serialization information for the expression: (Parameter p) => Int32.Parse(p.Value)

请指出我哪里错了。

最佳答案

如错误所示,您不能在查询中使用 Int32.Parse。此 lambda 表达式用于获取属性的名称,它不理解 Int32.Parse 是什么。

如果是查询字符串,需要使用字符串值进行比较:

var parameterQuery = Query.And(Query<Parameter>.EQ(p => p.ParamName, "Target Temperature"), Query<Parameter>.GT(p => p.Value, "15"));

但是,这可能不是您想要做的,因为您正在使用 GT。要被视为此比较的数字,您需要该值实际上是 mongo 中的 int,因此您需要更改属性的类型:

public class Parameter
{
    public string ParamName { get; set; }
    public ParamType ParamType { get; set; }
    public int Value { get; set; }
}

var parameterQuery = Query.And(Query<Parameter>.EQ(p => p.ParamName, "Target Temperature"), Query<Parameter>.GT(p => p.Value, 15));

关于c# - MongoDB Unable to determine the serialization information for the expression 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28039274/

相关文章:

c# - 下载前检查下载大小

C# 电子邮件到 gmail 标记为垃圾邮件,但来自雷鸟客户端的邮件正常发送(非垃圾邮件)

c# - 如何在 C# 中从指向内存流的 int 指针获取数据?

.net - 将信息从引用的类传递回调用表单

c# - 为 .net Framework 寻找无符号 128 位整数数据类型

ruby-on-rails - 用mongoid翻译rails中的模型属性的方法是什么?

c# - 控制台应用程序到服务

.net - 城堡温莎国际奥委会 : Passing constructor parameters to child components

c++ - Mongodb insert_many 性能 - C++

java - 如何在 MongoDB 和 OpenLDAP 数据库之间同步数据