【问题标题】:EF Core - Change column type from varchar to uuid in PostgreSQL 13: column cannot be cast automatically to type uuidEF Core - 在 PostgreSQL 13 中将列类型从 varchar 更改为 uuid:列无法自动转换为 uuid 类型
【发布时间】:2021-02-27 01:02:39
【问题描述】:

之前:

public class MyEntity
{
    public string Id { get; set; }
    //...
}

配置:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    //...

    modelBuilder.Entity<MyEntity>()
        .Property(e => e.Id)
        .ValueGeneratedOnAdd();
}

这是以前开发人员的代码,它导致列的 GUID 值。但是在 C# 中我必须处理字符串,所以我决定更改模型。

之后:

public class MyEntity
{
    public Guid Id { get; set; }
    //...
}

我从 Fluent API 配置中删除了 ValueGeneratedOnAdd() 代码。

我收到column "Id" cannot be cast automatically to type uuid 错误。

我认为此消息中的关键是automatically 字。

现在我的问题是,由于该列上的值已经是 GUID/UUID,有没有办法告诉 Postgres 将 varchar 类型更改为 uuid 并将当前字符串值转换为 UUID 并将其放入列?我猜应该有一个 SQL 脚本可以做到这一点而不会丢失任何数据。

【问题讨论】:

    标签: postgresql entity-framework-core entity-framework-migrations npgsql


    【解决方案1】:

    使用USING _columnname::uuid。这是一个插图。

    -- Prepare a test case:
    create table delme (x varchar);
    insert into delme (x) values 
     ('b575ec3a-2776-11eb-adc1-0242ac120002'),
     ('4d5c5440-2776-11eb-adc1-0242ac120002'),
     ('b575f25c-2776-11eb-adc1-0242ac120002');
    
    -- Here is the conversion that you need:
    ALTER TABLE delme ALTER COLUMN x TYPE uuid USING x::uuid;
    

    在您的特定情况下:

    ALTER TABLE "MyEntity" ALTER COLUMN "Id" TYPE uuid USING "Id"::uuid;
    

    顺便说一句,您的应用程序是数据库模型的唯一所有者吗?如果没有,那么更改现有表是个坏主意。

    【讨论】:

      猜你喜欢
      • 2013-12-19
      • 2021-01-26
      • 2020-08-11
      • 2014-02-27
      • 2023-02-08
      • 2011-02-05
      • 2012-10-21
      • 2014-10-26
      相关资源
      最近更新 更多