我正在测试Dapper,将对象加载/持久化到Oracle数据库,并管理Oracle的Guid存储。我需要一个SqlMapper.TypeHandler<Guid>
来处理Guid类型。当从数据库加载Guid列时,会调用Parse方法,但是当尝试使用Guid参数执行SQL语句时,会出现以下异常:
System.ArgumentException was unhandled; Message=Value does not fall within the expected range.Source=Oracle.DataAccess.
在调试中,我可以看到在从数据库加载我的类时调用了我的处理程序的Parse()方法,但没有调用SetValue()方法。
以下是复现异常的代码
CREATE TABLE foo (id RAW (16) NOT NULL PRIMARY KEY,
name VARCHAR2 (30) NOT NULL);
INSERT INTO foo (id, name) VALUES (SYS_GUID (), 'Bar');
COMMIT;
using System;
using System.Linq;
using Dapper;
using Oracle.DataAccess.Client;
namespace Program
{
public class Foo
{
public Guid Id { get; set; }
public string Name { get; set; }
}
class GuidTypeHandler : SqlMapper.TypeHandler<Guid>
{
public override Guid Parse(object value)
{
Console.WriteLine("Handling Parse of {0}", value);
var inVal = (byte[])value;
byte[] outVal = new byte[] { inVal[3], inVal[2], inVal[1], inVal[0], inVal[5], inVal[4], inVal[7], inVal[6], inVal[8], inVal[9], inVal[10], inVal[11], inVal[12], inVal[13], inVal[14], inVal[15] };
return new Guid(outVal);
}
public override void SetValue(System.Data.IDbDataParameter parameter, Guid value)
{
Console.WriteLine("Handling Setvalue of {0}", value);
var inVal = value.ToByteArray();
byte[] outVal = new byte[] { inVal[3], inVal[2], inVal[1], inVal[0], inVal[5], inVal[4], inVal[7], inVal[6], inVal[8], inVal[9], inVal[10], inVal[11], inVal[12], inVal[13], inVal[14], inVal[15] };
parameter.Value = outVal;
}
}
class Program
{
static void Main(string[] args)
{
SqlMapper.AddTypeHandler<Guid>(new GuidTypeHandler());
var conn = new OracleConnection(Resources.ConnectionString);
var def = new CommandDefinition("select id, name from foo");
conn.Open();
var foo = conn.Query<Foo>(def).First();
Console.WriteLine(foo.Id + "; " + foo.Name);
foo.Name = "New Bar";
def = new CommandDefinition(
"UPDATE foo SET name = :name WHERE id = :id",
parameters: new { ID = foo.Id, NAME = foo.Name });
var rows = conn.Execute(def);
Console.WriteLine("{0} rows inserted", rows);
Console.ReadLine();
}
}
}