C# 从LiteDB检索记录时出现InvalidCastException

C# 从LiteDB检索记录时出现InvalidCastException,c#,litedb,C#,Litedb,我通过LiteDb.Shell.exe插入了一条记录,当我试图在代码中检索该记录时,它抛出一个InvalidCastException。如果我试图通过shell查找记录,我会得到一个无法将类型为'System.Int32'的对象强制转换为类型为'System.String'。 这是我的模型 public class Query { public int Id { get; set; } public string FilePath { get; set; } public

我通过LiteDb.Shell.exe插入了一条记录,当我试图在代码中检索该记录时,它抛出一个
InvalidCastException
。如果我试图通过shell查找记录,我会得到一个
无法将类型为'System.Int32'的对象强制转换为类型为'System.String'。

这是我的模型

public class Query
{
    public int Id { get; set; }
    public string FilePath { get; set; }
    public string Hash { get; set; }
    public string[] Arguments { get; set; }
    public int[] PrintoutIds { get; set; }
}
这是我用来插入记录的shell命令

db.queries.insert {FilePath: "C:/Temp/Reporting Test.sql", Hash: "8074458BDE071C6B05A6EE1C718EC29CC92C89A2967D6E314EADEB0BA60F270E", Arguments: ["Tenant_ID"], PrintoutIds: [1]}
下面是我用来尝试恢复记录的shell命令

> db.queries.find
[1]: {"_id":{"$oid":"5a0ef5219996a32e14886d6b"},"FilePath":"C:/Temp/Reporting Test.sql","Hash":"8074458BDE071C6B05A6EE1C718EC29CC92C89A2967D6E314EADEB0BA60F270E","Arguments":["Tenant_ID"],"PrintoutIds":[1]}
> db.queries.find PrintoutIds contains 1
Unable to cast object of type 'System.Int32' to type 'System.String'.
> db.queries.find PrintoutIds contains "1"
> db.queries.find $.PrintoutIds[*] contains 1
Unable to cast object of type 'System.Int32' to type 'System.String'.
> db.queries.find $.PrintoutIds[*] contains "1"
这是我用来检索记录的代码

public IEnumerable<dynamic> DoStuffWithAQuery(int id)
{
    using (var reportDatabase = new LiteDatabase("C:/Stuff/Database/Reporting/Reports.db"))
    {
        var queryCollection = reportDatabase.GetCollection<Query>("queries");                                   
        queryCollection.EnsureIndex(x => x.PrintoutIds, "$.PrintoutIds[*]");
        Query query;
        try
        {
            // The next line throws an InvalidCastException.
            query = queryCollection.Find(x => x.PrintoutIds.Contains(id)).Single();
        }
        catch (InvalidOperationException)
        {
            throw new WebFaultException<string>("Only one query can be mapped to a printout",
                HttpStatusCode.BadRequest);
        }

        return DoSomeStuff(query);
    }
}
public IEnumerable DoStuffWithAQuery(int-id)
{
使用(var reportDatabase=newlitedatabase(“C:/Stuff/Database/Reporting/Reports.db”))
{
var queryCollection=reportDatabase.GetCollection(“查询”);
queryCollection.EnsureIndex(x=>x.printoutId,“$.printoutId[*]”;
查询;
尝试
{
//下一行抛出InvalidCastException。
query=queryCollection.Find(x=>x.PrintoutIds.Contains(id)).Single();
}
捕获(无效操作异常)
{
抛出新的WebFaultException(“只能将一个查询映射到打印输出”,
HttpStatusCode.BadRequest);
}
返回DoSomeStuff(查询);
}
}
这是我得到的完整的stacktrace

The server encountered an error processing the request. The exception message is 'Specified cast is not valid.'. See server logs for more details. The exception stack trace is:

at
 lambda_method(Closure , Object , Object ) at
 LiteDB.BsonMapper.DeserializeObject(Type type, Object obj, BsonDocument value) at
 LiteDB.BsonMapper.Deserialize(Type type, BsonValue value) at
 LiteDB.BsonMapper.ToObject(Type type, BsonDocument doc) at
 LiteDB.BsonMapper.ToObject[T](BsonDocument doc) at
 LiteDB.LiteCollection`1.<Find>d__17.MoveNext() at
 System.Linq.Enumerable.Single[TSource](IEnumerable`1 source) at
 ReportService.DoStuffWithAQuery(String tenantName, Int32 id, Object parameters) in C:\C# Workspace\MyProject\ReportService.cs:line 35 at
 SyncInvokeDoStuffWithAQuery(Object , Object[] , Object[] ) at
 System.ServiceModel.Dispatcher.SyncMethodInvoker.Invoke(Object instance, Object[] inputs, Object[]& outputs) at
 System.ServiceModel.Dispatcher.DispatchOperationRuntime.InvokeBegin(MessageRpc& rpc) at
 System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage5(MessageRpc& rpc) at
 System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage41(MessageRpc& rpc) at
 System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage4(MessageRpc& rpc) at
 System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage31(MessageRpc& rpc) at
 System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage3(MessageRpc& rpc) at
 System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage2(MessageRpc& rpc) at
 System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage11(MessageRpc& rpc) at
 System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage1(MessageRpc& rpc) at
 System.ServiceModel.Dispatcher.MessageRpc.Process(Boolean isOperationContextSet)
服务器在处理请求时遇到错误。异常消息为“指定的强制转换无效”。有关详细信息,请参阅服务器日志。异常堆栈跟踪为:
在
lambda_方法(闭包、对象、对象)
位于的LiteDB.BsonMapper.DeserializeObject(类型类型、对象对象、BsonDocument值)
在以下位置反序列化(类型类型,BsonValue)
LiteDB.BsonMapper.ToObject(类型,BsonDocument文档)位于
LiteDB.BsonMapper.ToObject[T](BsonDocument文档)位于
LiteDB.LiteCollection`1.d_u17.MoveNext()位于
System.Linq.Enumerable.Single[TSource](IEnumerable`1 source)位于
C:\C#Workspace\MyProject\ReportService.cs中的ReportService.DoStuffWithAQuery(字符串租户名称、Int32 id、对象参数):第35行
位于的SyncInvokedOfUffithAquery(对象,对象[],对象[])
System.ServiceModel.Dispatcher.SyncMethodInvoker.Invoke(对象实例、对象[]输入、对象[]输出)位于
位于的System.ServiceModel.Dispatcher.DispatchOperationRuntime.InvokeBegin(MessageRpc&rpc)
位于的System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage5(MessageRpc&rpc)
位于的System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage41(MessageRpc&rpc)
位于的System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage4(MessageRpc&rpc)
位于的System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage31(MessageRpc&rpc)
位于的System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage3(MessageRpc&rpc)
位于的System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage2(MessageRpc&rpc)
位于的System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage11(MessageRpc&rpc)
位于的System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage1(MessageRpc&rpc)
System.ServiceModel.Dispatcher.MessageRpc.Process(布尔isOperationContextSet)

这里有两种想法

首先,如果强类使用_id作为整数,则不能将shell与ObjectId(deafult)一起使用。尝试:

db.querys.insert{…}id:int

现在,您的文档将以自动id插入为
Int32
\u id:1
)。这将避免您的映射程序错误:

query=queryCollection.Find(x=>x.PrintoutIds.Contains(id)).Single()

第二,它是关于“包含”关键字的。在shell中,“contains”用作
字符串。contains
。Shell使用
Query.Contains(字符串字段、字符串文本)
。因此,不能将Int作为“text”传递

在shell中,您的查询必须使用
=

没有索引 db.querys.find$.PrintoutIds[*]=1

或者,创建一个索引 db.queries.ensureIndex PrintOutId使用$.PrintOutId[*]

现在,使用indexName db.querys.find PrintoutIds=1

但是。。。。。编写Linq表达式时,
Contains
可以来自
String
IEnumerable
。如果来自
字符串
,则与正常的
查询一样工作。包含
,但如果来自
IEnumerable
,则与
查询.EQ
一起工作

// QueryVisitor.cs : 152

// Contains (String): x.Name.Contains("auricio")
else if (method == "Contains" && type == typeof(string))
{
    var value = this.VisitValue(met.Arguments[0], null);

    return Query.Contains(this.GetField(met.Object, prefix), value);
}
// Contains (Enumerable): x.ListNumber.Contains(2)
else if (method == "Contains" && type == typeof(Enumerable))
{
    var field = this.GetField(met.Arguments[0], prefix);
    var value = this.VisitValue(met.Arguments[1], null);

    return Query.EQ(field, value);
}

将类查询中的Id更改为Query\u Id,这样就可以了

public int **Query_Id** { get; set; }