-
Notifications
You must be signed in to change notification settings - Fork 892
Open
Description
问题描述及重现代码:
根据文档,我写了针对于枚举类型映射的 TypeHandler
public class EnumTypeHandler : ITypeHandler
{
public EnumTypeHandler(Type type)
{
if (!type.IsEnum)
{
throw new ArgumentException($"{nameof(type)} is not a enum");
}
Type = type;
}
public object Deserialize(object value)
{
return EnumUtil.Parse(Type, value.ToString() ?? string.Empty);
}
public object Serialize(object value)
{
if (value is not Enum enumValue)
{
throw new ArgumentException($"{nameof(value)} is not an Enum");
}
var result = EnumUtil.AsString(enumValue);
return result ?? throw new ArgumentException($"{nameof(value)} is not a {nameof(Type)}");
}
public void FluentApi(ColumnFluent col)
{
col.MapType(typeof(string)).DbType("varchar(50)");
}
public Type Type { get; }
}使用 Aop 方式对枚举类型新增 typehandler
freeSql.Aop.ConfigEntityProperty += (_, e) =>
{
if (e.Property.PropertyType.IsEnum)
{
var handler = new EnumTypeHandler(e.Property.PropertyType);
Internal.Utils.TypeHandlers.TryAdd(handler.Type, handler);
e.ModifyResult.MapType = typeof(string);
}
};在不使用 e.ModifyResult.MapType = typeof(string) 时
使用 repository.InsertAsync 不会使用 TypeHandler 来处理枚举
此时数据库像这样
加入后,值会使用 TypeHandler 转换
但是使用 _repository.Select.Where(k => k.Type == keyType) 时,由于此处代码的处理,会优先走枚举 string 的特殊处理,导致报错
FreeSql/FreeSql/Internal/CommonExpression.cs
Lines 961 to 974 in 8559c67
| if (right != "NULL" && isLeftMapType && | |
| //判断参数化后的bug | |
| !(right.Contains('@') || right.Contains('?') || right.Contains(':')) && | |
| //三元表达式后,取消此条件 #184 | |
| tsc.mapType != null) | |
| { | |
| var enumType = leftMapColumn.CsType.NullableTypeOrThis(); | |
| if (enumType.IsEnum) | |
| { | |
| rightMapColumn = SearchColumnByField(tsc._tables, tsc.currentTable, right); | |
| if (rightMapColumn == null) | |
| right = formatSql(Enum.Parse(enumType, right.StartsWith("N'") ? right.Substring(1).Trim('\'') : right.Trim('\'')), leftMapColumn.Attribute.MapType, leftMapColumn, tsc.dbParams); | |
| } | |
| } |
报错如下
ArgumentException: Requested value 'asymmetric1' was not found.
System.Enum.TryParseByName<TStorage>(RuntimeType enumType, ReadOnlySpan<char> value, bool ignoreCase, bool throwOnFailure, out TStorage result)
在不使用 e.ModifyResult.MapType = typeof(string) 时,Select 正常
数据库版本
PostgreSQL 18.0 (Debian 18.0-1.pgdg13+3) on x86_64-pc-linux-gnu, compiled by gcc (Debian 14.2.0-19) 14.2.0, 64-bit
安装的Nuget包
FreeSql.DbContext 3.5.213
FreeSql.Extensions.JsonMap 3.5.213
FreeSql.Provider.PostgreSQL 3.5.213
.net framework/. net core? 及具体版本
.net 9.0
Metadata
Metadata
Assignees
Labels
No labels