Dapper,tinyint(1), Error parsing column ...
出錯條件:
1.實體屬性為bool?類型
2.對應欄位為可空的tinyint(1)類型
3.該欄位查詢結果內即含有null,又含有正常值
google答案,兩種建議:
1.修改sql語句,直接cast轉換(未通過)
2.修改欄位類型為tinyint長度為2或更長(此法可行,測試發現,改成bit類型也行),在datareader 的getfieldtype時,tinyint長度為1類型為Boolean,大於1時類型為byte,short,int
然,因我的查詢結果中此類欄位數量較多,且以上兩種方案並不滿意,也不符合我的需求,故想自己另覓答案:
首先,想到修改源碼,為開源做貢獻。發現它是長這樣的:
private static Func<IDataReader, object> GetTypeDeserializerImpl( Type type, IDataReader reader, int startBound = 0, int length = -1, bool returnNullIfFirstMissing = false ) { var returnType = type.IsValueType() ? typeof(object) : type; var dm = new DynamicMethod("Deserialize" + Guid.NewGuid().ToString(), returnType, new[] { typeof(IDataReader) }, type, true); var il = dm.GetILGenerator(); il.DeclareLocal(typeof(int)); il.DeclareLocal(type); il.Emit(OpCodes.Ldc_I4_0); il.Emit(OpCodes.Stloc_0); if (length == -1) { length = reader.FieldCount - startBound; } if (reader.FieldCount <= startBound) { throw MultiMapException(reader); } //資料庫欄位名 var fieldNames = Enumerable.Range(startBound, length).Select(i => reader.GetName(i)).ToArray(); //ITypeMap 含type的欄位,屬性 ITypeMap typeMap = GetTypeMap(type); int index = startBound; ConstructorInfo specializedConstructor = null; #if !NETSTANDARD1_3 bool supportInitialize = false; #endif Dictionary<Type, LocalBuilder> structLocals = null; if (type.IsValueType()) { il.Emit(OpCodes.Ldloca_S, (byte)1); il.Emit(OpCodes.Initobj, type); } else { //欄位映射,開始 var types = new Type[length]; for (int i = startBound; i < startBound + length; i++) { types[i - startBound] = reader.GetFieldType(i); } //獲取ExplicitConstructor特性的構造函數 var explicitConstr = typeMap.FindExplicitConstructor(); if (explicitConstr != null) { var consPs = explicitConstr.GetParameters(); foreach (var p in consPs) { if (!p.ParameterType.IsValueType()) { il.Emit(OpCodes.Ldnull); } else { GetTempLocal(il, ref structLocals, p.ParameterType, true); } } il.Emit(OpCodes.Newobj, explicitConstr); il.Emit(OpCodes.Stloc_1); #if !NETSTANDARD1_3 supportInitialize = typeof(ISupportInitialize).IsAssignableFrom(type); if (supportInitialize) { il.Emit(OpCodes.Ldloc_1); il.EmitCall(OpCodes.Callvirt, typeof(ISupportInitialize).GetMethod(nameof(ISupportInitialize.BeginInit)), null); } #endif } else { //按構造函數參數個數倒序排列,查找合適的構造函數 var ctor = typeMap.FindConstructor(fieldNames, types); if (ctor == null) { string proposedTypes = "(" + string.Join(", ", types.Select((t, i) => t.FullName + " " + fieldNames[i]).ToArray()) + ")"; throw new InvalidOperationException($"A parameterless default constructor or one matching signature {proposedTypes} is required for {type.FullName} materialization"); } //無參構造 if (ctor.GetParameters().Length == 0) { //用指定構造函數創建一個新實例,賦值給類型變數 il.Emit(OpCodes.Newobj, ctor); il.Emit(OpCodes.Stloc_1); #if !NETSTANDARD1_3 supportInitialize = typeof(ISupportInitialize).IsAssignableFrom(type); if (supportInitialize) { //取type實例 il.Emit(OpCodes.Ldloc_1); //調用公共方法 il.EmitCall(OpCodes.Callvirt, typeof(ISupportInitialize).GetMethod(nameof(ISupportInitialize.BeginInit)), null); } #endif } else { specializedConstructor = ctor; } } } //try塊開始 il.BeginExceptionBlock(); //值類型 if (type.IsValueType()) { il.Emit(OpCodes.Ldloca_S, (byte)1);// [target] } else if (specializedConstructor == null) { il.Emit(OpCodes.Ldloc_1);// [target] } //根據資料庫欄位名,查找傳入類型中對應的屬性Property,若沒有則查找欄位Field var members = IsValueTuple(type) ? GetValueTupleMembers(type, fieldNames) : ((specializedConstructor != null ? fieldNames.Select(n => typeMap.GetConstructorParameter(specializedConstructor, n)) : fieldNames.Select(n => typeMap.GetMember(n))).ToList()); // stack is now [target] bool first = true; var allDone = il.DefineLabel(); int enumDeclareLocal = -1, valueCopyLocal = il.DeclareLocal(typeof(object)).LocalIndex; bool applyNullSetting = Settings.ApplyNullValues; foreach (var item in members) { if (item != null) { if (specializedConstructor == null) il.Emit(OpCodes.Dup); // stack is now [target][target] Label isDbNullLabel = il.DefineLabel(); Label finishLabel = il.DefineLabel(); //索引為0的參數即reader il.Emit(OpCodes.Ldarg_0); // stack is now [target][target][reader] EmitInt32(il, index); // stack is now [target][target][reader][index] il.Emit(OpCodes.Dup);// stack is now [target][target][reader][index][index] il.Emit(OpCodes.Stloc_0);// stack is now [target][target][reader][index] il.Emit(OpCodes.Callvirt, getItem); // stack is now [target][target][value-as-object] il.Emit(OpCodes.Dup); // stack is now [target][target][value-as-object][value-as-object] StoreLocal(il, valueCopyLocal); //欄位類型 Type colType = reader.GetFieldType(index);//tinyint(1) null //屬性/欄位類型 Type memberType = item.MemberType;//bool? if (memberType == typeof(char) || memberType == typeof(char?)) { il.EmitCall(OpCodes.Call, typeof(SqlMapper).GetMethod( memberType == typeof(char) ? nameof(SqlMapper.ReadChar) : nameof(SqlMapper.ReadNullableChar), BindingFlags.Static | BindingFlags.Public), null); // stack is now [target][target][typed-value] } else { il.Emit(OpCodes.Dup); // stack is now [target][target][value][value] il.Emit(OpCodes.Isinst, typeof(DBNull)); // stack is now [target][target][value-as-object][DBNull or null] //跳轉到marklable il.Emit(OpCodes.Brtrue_S, isDbNullLabel); // stack is now [target][target][value-as-object] // unbox nullable enums as the primitive, i.e. byte etc var nullUnderlyingType = Nullable.GetUnderlyingType(memberType); var unboxType = nullUnderlyingType?.IsEnum() == true ? nullUnderlyingType : memberType; if (unboxType.IsEnum()) { Type numericType = Enum.GetUnderlyingType(unboxType); if (colType == typeof(string)) { if (enumDeclareLocal == -1) { enumDeclareLocal = il.DeclareLocal(typeof(string)).LocalIndex; } il.Emit(OpCodes.Castclass, typeof(string)); // stack is now [target][target][string] StoreLocal(il, enumDeclareLocal); // stack is now [target][target] il.Emit(OpCodes.Ldtoken, unboxType); // stack is now [target][target][enum-type-token] il.EmitCall(OpCodes.Call, typeof(Type).GetMethod(nameof(Type.GetTypeFromHandle)), null);// stack is now [target][target][enum-type] LoadLocal(il, enumDeclareLocal); // stack is now [target][target][enum-type][string] il.Emit(OpCodes.Ldc_I4_1); // stack is now [target][target][enum-type][string][true] il.EmitCall(OpCodes.Call, enumParse, null); // stack is now [target][target][enum-as-object] il.Emit(OpCodes.Unbox_Any, unboxType); // stack is now [target][target][typed-value] } else { FlexibleConvertBoxedFromHeadOfStack(il, colType, unboxType, numericType); } if (nullUnderlyingType != null) { il.Emit(OpCodes.Newobj, memberType.GetConstructor(new[] { nullUnderlyingType })); // stack is now [target][target][typed-value] } } else if (memberType.FullName == LinqBinary) { il.Emit(OpCodes.Unbox_Any, typeof(byte[])); // stack is now [target][target][byte-array] il.Emit(OpCodes.Newobj, memberType.GetConstructor(new Type[] { typeof(byte[]) }));// stack is now [target][target][binary] } else { TypeCode dataTypeCode = TypeExtensions.GetTypeCode(colType), unboxTypeCode = TypeExtensions.GetTypeCode(unboxType); bool hasTypeHandler; if ((hasTypeHandler = typeHandlers.ContainsKey(unboxType)) || colType == unboxType || dataTypeCode == unboxTypeCode || dataTypeCode == TypeExtensions.GetTypeCode(nullUnderlyingType)) { if (hasTypeHandler) { #pragma warning disable 618 il.EmitCall(OpCodes.Call, typeof(TypeHandlerCache<>).MakeGenericType(unboxType).GetMethod(nameof(TypeHandlerCache<int>.Parse)), null); // stack is now [target][target][typed-value] #pragma warning restore 618 } else { il.Emit(OpCodes.Unbox_Any, unboxType); // stack is now [target][target][typed-value] } } else { // not a direct match; need to tweak the unbox FlexibleConvertBoxedFromHeadOfStack(il, colType, nullUnderlyingType ?? unboxType, null); if (nullUnderlyingType != null) { il.Emit(OpCodes.Newobj, unboxType.GetConstructor(new[] { nullUnderlyingType })); // stack is now [target][target][typed-value] } } } } if (specializedConstructor == null) { // Store the value in the property/field if (item.Property != null) { il.Emit(type.IsValueType() ? OpCodes.Call : OpCodes.Callvirt, DefaultTypeMap.GetPropertySetter(item.Property, type)); } else { il.Emit(OpCodes.Stfld, item.Field); // stack is now [target] } } //跳轉到finishLabel il.Emit(OpCodes.Br_S, finishLabel); // stack is now [target] il.MarkLabel(isDbNullLabel); // incoming stack: [target][target][value] if (specializedConstructor != null) { il.Emit(OpCodes.Pop); if (item.MemberType.IsValueType()) { int localIndex = il.DeclareLocal(item.MemberType).LocalIndex; LoadLocalAddress(il, localIndex); il.Emit(OpCodes.Initobj, item.MemberType); LoadLocal(il, localIndex); } else { il.Emit(OpCodes.Ldnull); } } else if (applyNullSetting && (!memberType.IsValueType() || Nullable.GetUnderlyingType(memberType) != null)) { il.Emit(OpCodes.Pop); // stack is now [target][target] // can load a null with this value if (memberType.IsValueType()) { // must be Nullable<T> for some T GetTempLocal(il, ref structLocals, memberType, true); // stack is now [target][target][null] } else { // regular reference-type il.Emit(OpCodes.Ldnull); // stack is now [target][target][null] } // Store the value in the property/field if (item.Property != null) { il.Emit(type.IsValueType() ? OpCodes.Call : OpCodes.Callvirt, DefaultTypeMap.GetPropertySetter(item.Property, type)); // stack is now [target] } else { il.Emit(OpCodes.Stfld, item.Field); // stack is now [target] } } else { il.Emit(OpCodes.Pop); // stack is now [target][target] il.Emit(OpCodes.Pop); // stack is now [target] } if (first && returnNullIfFirstMissing) { il.Emit(OpCodes.Pop); il.Emit(OpCodes.Ldnull); // stack is now [null] il.Emit(OpCodes.Stloc_1); il.Emit(OpCodes.Br, allDone); } il.MarkLabel(finishLabel); } first = false; index++; } if (type.IsValueType()) { il.Emit(OpCodes.Pop); } else { if (specializedConstructor != null) { il.Emit(OpCodes.Newobj, specializedConstructor); } il.Emit(OpCodes.Stloc_1); // stack is empty #if !NETSTANDARD1_3 if (supportInitialize) { il.Emit(OpCodes.Ldloc_1); il.EmitCall(OpCodes.Callvirt, typeof(ISupportInitialize).GetMethod(nameof(ISupportInitialize.EndInit)), null); } #endif } il.MarkLabel(allDone); il.BeginCatchBlock(typeof(InvalidCastException)); // stack is Exception il.Emit(OpCodes.Ldloc_0); // stack is Exception, index il.Emit(OpCodes.Ldarg_0); // stack is Exception, index, reader LoadLocal(il, valueCopyLocal); // stack is Exception, index, reader, value il.EmitCall(OpCodes.Call, typeof(SqlMapper).GetMethod(nameof(SqlMapper.ThrowDataException)), null); il.EndExceptionBlock(); il.Emit(OpCodes.Ldloc_1); // stack is [rval] if (type.IsValueType()) { il.Emit(OpCodes.Box, type); } il.Emit(OpCodes.Ret); var funcType = System.Linq.Expressions.Expression.GetFuncType(typeof(IDataReader), returnType); return (Func<IDataReader, object>)dm.CreateDelegate(funcType); }View Code
一個長達三百行的方法,創建一個動態方法:將datarecord轉換為目標類型。瞬間放棄了
其次,擴展方法
通讀上面的方法GetTypeDeserializerImpl,配合調試
查看生成的動態方法,是這樣的
public class Test { public WXDish Deserialize0cfe6fe6-2ac9-4880-8cb7-c838a493b2a6(IDataReader dataReader) { int num = 0; WXDish wXDish = new WXDish(); checked { try { WXDish expr_09 = wXDish; object obj; object expr_DF = obj = ((IDataRecord)this)[num = 7]; if (!(expr_DF is DBNull)) { expr_09.set_IsRecommended((bool)expr_DF); } object expr_101 = obj = ((IDataRecord)this)[num = 8]; if (!(expr_101 is DBNull)) { expr_09.set_IsNew((bool)expr_101); } object expr_124 = obj = ((IDataRecord)this)[num = 9]; if (!(expr_124 is DBNull)) { expr_09.set_IsEnabled((bool?)expr_124); } object expr_147 = obj = ((IDataRecord)this)[num = 10]; if (!(expr_147 is DBNull)) { expr_09.set_IsDiscount((bool?)expr_147); } object expr_16A = obj = ((IDataRecord)this)[num = 11]; if (!(expr_16A is DBNull)) { expr_09.set_DiscountRate((double?)expr_16A); } object expr_18D = obj = ((IDataRecord)this)[num = 12]; if (!(expr_18D is DBNull)) { expr_09.set_IsScore((bool?)expr_18D); } object expr_62A = obj = ((IDataRecord)this)[num = 53]; if (!(expr_62A is DBNull)) { expr_09.set_ImageName((string)expr_62A); } object expr_64D = obj = ((IDataRecord)this)[num = 54]; if (!(expr_64D is DBNull)) { expr_09.set_CookBookCategory((int)expr_64D); } wXDish = expr_09; } catch (Exception arg_66E_0) { object obj; SqlMapper.ThrowDataException(arg_66E_0, num, this, obj); } return wXDish; } } }View Code
測試發現,(bool?)object 0轉換錯誤。
源碼中發現
if ((hasTypeHandler = typeHandlers.ContainsKey(unboxType)) || colType == unboxType || dataTypeCode == unboxTypeCode || dataTypeCode == TypeExtensions.GetTypeCode(nullUnderlyingType)) { if (hasTypeHandler) { #pragma warning disable 618 il.EmitCall(OpCodes.Call, typeof(TypeHandlerCache<>).MakeGenericType(unboxType).GetMethod(nameof(TypeHandlerCache<int>.Parse)), null); // stack is now [target][target][typed-value] #pragma warning restore 618 } else { il.Emit(OpCodes.Unbox_Any, unboxType); // stack is now [target][target][typed-value] } }View Code
考慮通過擴展typehandlers,自定義該類欄位轉換
public class BoolConvert : SqlMapper.TypeHandler<bool?> { public override void SetValue(IDbDataParameter parameter, bool? value) { // never hit throw new NotImplementedException(); } public override bool? Parse(object value) { var val = value as sbyte?; if (val != null) { var result = Convert.ToBoolean(val); return result; } return (bool?)value; } }View Code
在使用dapper的query前 通過SqlMapper.AddTypeHandler註冊該轉換
測試通過。1天時間,紀念一下