Dapper官方库 在guid和string互转的问题
之前在和老何谈论他的开源项目Util中使用MySql的过程中发现了官方dapper在转换guid到string时候的一个错误
Error parsing column 0 (ID=6c2adb93-d81a-4fda-8e25-c6e90d4ebaaa - Object)
在官方github提了issue但一直没有给到更新和回复,其实解决方案也是非常简单的,利用dapper的TypeHandler处理下转换的过程即可
public class StringGuidHandler:SqlMapper.TypeHandler<string> { public override void SetValue(IDbDataParameter parameter, string value) { parameter.Value = value; } public override string Parse(object value) { return value.ToString(); } }
之后全局加入即可(此处为了方便以console为例)
using Dapper; using System; using System.Data.SqlClient; namespace GuidDemo { class Program { static void Main(string[] args) { try { SqlMapper.AddTypeHandler(typeof(string), new StringGuidHandler()); string sqlString = "server=192.168.1.3;uid=sa;pwd=demo$;database=demo;"; using (SqlConnection conn = new SqlConnection(sqlString)) { conn.Open();//打开连接 string strSql = @"SELECT * from Test_002 WHERE Name='sa'"; Test_002 count = conn.QueryFirst<Test_002>(strSql); var testObject=new Test_002(){ID =Guid.NewGuid().ToString(),Name = "b"}; conn.Execute($"insert into Test_002 (Id,Name) values ({testObject.ID},{testObject.Name})"); } } catch(Exception e) { } } } } using System.Data; using Dapper; namespace GuidDemo { public class StringGuidHandler:SqlMapper.TypeHandler<string> { public override void SetValue(IDbDataParameter parameter, string value) { parameter.Value = value; } public override string Parse(object value) { return value.ToString(); } } }