【发布时间】:2017-04-14 22:37:48
【问题描述】:
我对 .Net 中的 Sqlite 没有太多经验,但我看到的行为很奇怪。假设我们有一个带有以下project.json 的.Net 核心应用程序:
{
"version": "1.0.0-*",
"buildOptions": {
"debugType": "portable",
"emitEntryPoint": true
},
"dependencies": {
"Microsoft.Data.Sqlite": "1.0.0",
"Dapper": "1.50.2"
},
"frameworks": {
"netcoreapp1.0": {
"dependencies": {
"Microsoft.NETCore.App": {
"type": "platform",
"version": "1.0.0"
}
},
"imports": "dnxcore50"
}
}
}
我们还有一个简单的类Item:
public class Item
{
public Item() { }
public Item(int id, string name, decimal price)
{
this.Id = id;
this.Name = name;
this.Price = price;
}
public int Id { get; set; }
public string Name { get; set; }
public decimal Price { get; set; }
}
然后我创建一个内存数据库并用数据填充它(使用 Dapper):
var connection = new SqliteConnection("Data Source=:memory:");
connection.Open();
connection.Execute("CREATE TABLE IF NOT EXISTS Items(Id INT, Name NVARCHAR(50), Price DECIMAL)");
var items = new List<Item>
{
new Item(1, "Apple", 3m),
new Item(2, "Banana", 1.4m)
};
connection.Execute("INSERT INTO Items(Id, Name, Price) VALUES (@Id, @Name, @Price)", items);
然后我尝试从Items 表中读取:
var dbItems = connection.Query<Item>("SELECT Id, Name, Price FROM Items").ToList();
当我运行解决方案时,出现以下异常:
未处理的异常:System.InvalidOperationException:解析错误 第 2 列(价格 = 1.4 - 双倍)---> System.Invali dCastException: 无法将“System.Double”类型的对象转换为“System.Int64”类型。
好的,那我尝试使用Microsoft.Data.Sqlite获取数据:
var command = connection.CreateCommand();
command.CommandText = "SELECT Price FROM Items";
var reader = command.ExecuteReader();
while (reader.Read())
{
Console.WriteLine(reader[0].GetType());
}
结果我得到:
System.Int64 // Price = 3
System.Double // Price = 1.4
我尝试使用小数价格在真实数据库上运行查询,返回的数据类型正确且始终为十进制(如预期的那样)。
我应该进一步挖掘什么方向?我的内存数据库有问题吗?如何使其与小数一致?
【问题讨论】:
标签: c# sqlite dapper .net-core