- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我目前正在使用 postgres 枚举
CREATE TYPE http_action_enum AS ENUM ('GET', 'HEAD', 'POST', 'PUT', 'DELETE', 'CONNECT', 'OPTIONS', 'TRACE', 'PATCH');
CREATE TABLE IF NOT EXISTS response
(
id UUID PRIMARY KEY,
http_action http_action_enum NOT NULL
);
但是当我使用 ef 框架插入到 postgres 数据库时,我一直遇到以下错误:
Exception data:
Severity: ERROR
SqlState: 42804
MessageText: column "destination" is of type source_dest_enum but expression is of type integer
Hint: You will need to rewrite or cast the expression.
当我检查响应数据类型时,它实际上是正确的枚举而不是整数。
存储库.cs
public async Task<Response> InsertRecord(Response response, CancellationToken cancellationToken)
{
await dBContext.response.AddAsync(response, cancellationToken).ConfigureAwait(true);
await dBContext.SaveChangesAsync(cancellationToken).ConfigureAwait(true);
return response;
}
数据库上下文.cs
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.HasDefaultSchema("public");
modelBuilder.HasPostgresEnum<SourceDestinationEnum>();
modelBuilder.HasPostgresEnum<HttpActionEnum>();
modelBuilder.Entity<Response>().Property(d => d.RespondedData).HasColumnType("json");
HttpActionEnum.cs
[JsonConverter(typeof(StringEnumConverter))]
public enum HttpActionEnum
{
GET,
POST,
}
有没有人遇到过将 c# 枚举映射到 postgres 枚举并可以提供建议?
我尝试转换为枚举,但失败并出现错误,指出该列是枚举类型,但表达式是文本类型。
https://learn.microsoft.com/en-us/ef/core/modeling/value-conversions
DBContext.cs(更新)
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.HasDefaultSchema("public");
modelBuilder.HasPostgresEnum<SourceDestinationEnum>();
modelBuilder.HasPostgresEnum<HttpActionEnum>();
modelBuilder.Entity<Response>(entity =>
{
entity.Property(e => e.RespondedData).HasColumnType("json");
entity.Property(e => e.Destination).HasConversion(
v => v.ToString(),
v => (SourceDestinationEnum)System.Enum.Parse(typeof(SourceDestinationEnum), v));
});
错误
+ InnerException {"42804: column \"destination\" is of type source_dest_enum but expression is of type text"} System.Exception {Npgsql.PostgresException}
最佳答案
在此处查看有关 postgres 枚举的 Entity Framework 文章:https://www.npgsql.org/efcore/mapping/enum.html?tabs=tabid-1
Even if your database enum is created, Npgsql has to know about it, and especially about your CLR enum type that should be mapped to it. This is done by adding the following code, before any EF Core operations take place. An appropriate place for this is in the static constructor on your DbContext class:
static MyDbContext()
=> NpgsqlConnection.GlobalTypeMapper.MapEnum<Mood>();
对于非 EF 情况,请在此处查看信息:https://www.npgsql.org/doc/types/enums_and_composites.html
关于C# 枚举到 postgres 枚举,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63590759/
我是一名优秀的程序员,十分优秀!