简体   繁体   English

EF Core - 在 PostgreSQL 中将列类型从 varchar 更改为 uuid 13:列无法自动转换为类型 uuid

[英]EF Core - Change column type from varchar to uuid in PostgreSQL 13: column cannot be cast automatically to type uuid

Before:前:

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

Config:配置:

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

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

This was the previous developer's code which resulted in GUID values for the column.这是先前开发人员的代码,它为该列生成了 GUID 值。 But in C# I had to deal with strings, so I decided to change the model.但是在C#我要处理字符串,所以我决定改model。

After:后:

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

And I removed the ValueGeneratedOnAdd() code from Fluent API config.我从 Fluent API 配置中删除了ValueGeneratedOnAdd()代码。

I get the column "Id" cannot be cast automatically to type uuid error.我收到column "Id" cannot be cast automatically to type uuid错误。

I think the key in this message is the automatically word.我认为此消息中的关键是“ automatically ”一词。

Now my question is that since the values on that column are already GUID/UUID, is there any way to tell Postgres to change the varchar type to uuid and cast the current string value to UUID and put it in the column?现在我的问题是,由于该列上的值已经是 GUID/UUID,是否有任何方法可以告诉 Postgres 将varchar类型更改为uuid并将当前字符串值转换为 UUID 并将其放入列中? I'm guessing there should be a SQL script that can do this without any data loss.我猜应该有一个 SQL 脚本可以做到这一点而不会丢失任何数据。

Use USING _columnname::uuid .使用USING _columnname::uuid Here is an illustration.这是一个例子。

-- 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;

In your particular case:在您的特定情况下:

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

Btw, is your application the sole owner of the database model?顺便说一句,您的应用程序是数据库 model 的唯一所有者吗? If not then changing an existing table is a bad idea.如果不是,则更改现有表不是一个好主意。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM