2

我在 SQL Server 中使用 dapper,但在我的单元测试中使用 Sqlite 进行一些内存测试。

我有一堂课如下

public class Test
{
  public int ID {get;set;}
  public string Name 
}

如果我使用带有 SQL Server 连接的 dapper 进行查询,它工作正常。

如果我使用带有 SQLite 连接的 dapper 进行查询,则会收到类型转换错误。基本上我需要将 ID 的类型更改为 long,而不是 int。

我不想在 SQL Server 中更改我的架构,所以我想知道该场景是否有解决方法。我尝试使用隐式强制转换为 long/int 创建和 ID 类,但这也失败了,而且我没有想法!

4

2 回答 2

0

This revolves around the fact that Dapper uses the GetValue method on the IDataRecord interface. The concrete class in the System.Data.SqlLite namespace probably map values differently than that of System.Data.SqlClient.

As @FelicePollano pointed out try changing the structure of the SQLLite table and see if that causes the concrete class in System.Data.SqlLite to map it differently.

Another option is to roll your own mapping using the FastExpando object Dapper returns and force it to convert the value to a Int.

IEnumerable<dynamic> results = Conn.Query("Select ID from SomeTable");

var testValue = new Test
{
    ID = Convert.ToInt32(Results[0].ID.ToString())
};

Not really a big fan of it because it could require a lot of code changes, but it can work.

Please note: That example code can throw a exception if the ID column is not an integer. You can use TryParse, but for the sake of brevity I didn't include it.

于 2012-07-20T15:24:52.663 回答
0

尝试创建将 INTEGER 的长度指定为 4 个字节的 sqlite 表。也许这个问题也会有所帮助:SQLite 整数数据类型(如 int、integer、bigint 等)有什么区别?

于 2012-07-19T16:21:06.460 回答