7

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. But in C# I had to deal with strings, so I decided to change the model.

After:

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

And I removed the ValueGeneratedOnAdd() code from Fluent API config.

I get the column "Id" cannot be cast automatically to type uuid error.

I think the key in this message is the automatically word.

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? I'm guessing there should be a SQL script that can do this without any data loss.

2 Answers 2

14

Use 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? If not then changing an existing table is a bad idea.

14

You can use EF migrations for this task too. But you have to modify the generated migration code from

migrationBuilder.AlterColumn<Guid>(
            name: "Id",
            table: "Users",
            type: "uuid",
            nullable: false,
            oldClrType: typeof(string),
            oldType: "text");

to

migrationBuilder.AlterColumn<Guid>(
            name: "Id",
            table: "Users",
            type: "uuid using \"Id\"::uuid",
            nullable: false,
            oldClrType: typeof(string),
            oldType: "text");

The important part is: type: "uuid using \"Id\"::uuid"

2
  • 1
    I was looking for a way to add "using" to ef core migrations. Thank you Commented May 15, 2023 at 5:44
  • 2
    Thanks Michael. it's work for me if you add parenthesis migrationBuilder.AlterColumn<Guid>( name: "Id", table: "Users", type: "uuid using (\"Id\"::uuid)", nullable: false, oldClrType: typeof(string), oldType: "text");
    – m.benissa
    Commented Nov 2, 2023 at 19:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.