dotnetcore / dotnetcore/FreeSql

对枚举类型使用 TypeHandler,Update 和 Select 冲突

Open
#2,113 2 comments 0 reactions 0 assignees View on GitHub
Dominant language
C#
Stars
4.4k
Forks
910
PR merge metrics
No merged PRs in 30d

Description

#### 问题描述及重现代码:
根据文档,我写了针对于枚举类型映射的 TypeHandler
```c#
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
```c#
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 来处理枚举
此时数据库像这样

Image

加入后,值会使用 TypeHandler 转换

Image

但是使用 `_repository.Select.Where(k => k.Type == keyType)` 时,由于此处代码的处理,会优先走枚举 string 的特殊处理,导致报错
https://github.com/dotnetcore/FreeSql/blob/8559c6730bcf04fa0846ceb5a96dd4c2408e9609/FreeSql/Internal/CommonExpression.cs#L961-L974

报错如下
```
ArgumentException: Requested value 'asymmetric1' was not found.
System.Enum.TryParseByName(RuntimeType enumType, ReadOnlySpan 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

Contributor guide

No contributing guide indexed for this repository

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.