我有一个类Sample
,其中一个属性是枚举,TargetType
。我samples
在 PostgreSQL 数据库中定义了一个相应的表,以及一个匹配的枚举类型targettypes
.
使用 Dapper.FastCRUD,我可以成功地从表中检索记录。但是,在插入过程中出现错误:
Npgsql.PostgresException (0x80004005): 42804: column "target_type" is of type targettype but expression is of type integer
编辑 1: MoonStorm - Dapper.FastCRUD 的创建者 - 澄清 DB-CLR 类型转换由 Dapper 处理。所以,现在的问题是:
我如何告诉 Dapper 将 C# 映射enum TargetType
到 PostgreSQL ENUM TYPE targettype
?
枚举定义为:
public enum TargetType
{
[NpgsqlTypes.PgName("Unknown")]
UNKNOWN = 0,
[NpgsqlTypes.PgName("Animal")]
ANIMAL = 1,
[NpgsqlTypes.PgName("Car")]
CAR = 2,
[NpgsqlTypes.PgName("Truck")]
TRUCK = 3
}
该类定义为:
[Table("samples")]
public partial class Sample
{
[Column("recording_time")]
public DateTime RecordingTime { get; set; }
[Column("x_position")]
public double X_Position { get; set; }
[Column("x_velocity")]
public double X_Velocity { get; set; }
[Column("y_position")]
public double Y_Position { get; set; }
[Column("y_velocity")]
public double Y_Velocity { get; set; }
[Key]
[Column("id")]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public ulong Id { get; set; }
[Column("target_type")] // <--- This is the offending column
public TargetType TargetType { get; set; }
}
编辑 2:使用工作插入修改了示例。
用法说明:
using Npgsql;
using Dapper.FastCrud;
...
NpgsqlConnection.MapEnumGlobally<TargetType>("public.targettype"); // ... (1)
OrmConfiguration.DefaultDialect = SqlDialect.PostgreSql;
(using NpgsqlConnection conn = ...) // Connect to database
{
var samples = conn.Find<Sample>(); // <--- This works correctly
foreach (Sample s in samples)
Console.WriteLine(s);
... // Generate new samples
using (var writer = conn.BeginBinaryImport(sql))
{
foreach (Sample s in entities)
{
writer.StartRow();
writer.Write(s.TargetType); // <--- This insert works, due to (1)
...
}
}
foreach (Sample sample in sampleList)
conn.Insert<Sample>(sample); // <--- This throws PostgresException
...
}