Add computed column with fluent migrator

234 views Asked by At

I've got a table that has a JSON content property. I wish to extract with a computed column a value I'm sure it's inside that field. I've used it in the past json_value. How can I define a computed column in fluent migrator?

My migration is defined as


    [Migration(202304031401, "somedesc.")]
    public class AddProductTableMigration:Migration
    {
        public static string TableName = "xxx";
    
        public override void Up()
        {
            Create.Table(TableName).InSchema("dbo")
                .WithColumn("Id").AsInt32().NotNullable().Unique()
                .WithColumn("JsonContent").AsCustom("nvarchar(max)").NotNullable();
        }

        public override void Down()
        {
            if (Schema.Table(TableName).Exists())
            {
                Delete.Table(TableName);
            }
        }
    }
1

There are 1 answers

0
Caltor On

You can create a computed column using the AsCustom(...) method like this:

Create.Column("DevelopmentType").OnTable("Software").AsCustom(@"
 AS (
  CASE
   WHEN IsJS = 1 THEN 'JavaScript'
   WHEN IsPython = 1 THEN 'Python'
   ELSE 'Unknown'
  END
 )
 PERSISTED
");

Or you can use the Execute.Sql(...) method like this:

Execute.Sql(@"
ALTER TABLE Software ADD DevelopmentType
 AS (
  CASE
   WHEN IsJS = 1 THEN 'JavaScript'
   WHEN IsPython = 1 THEN 'Python'
   ELSE 'Unknown'
  END
 )
 PERSISTED
");

Source https://groups.google.com/g/fluentmigrator-google-group/c/Jtbdjd35tlg/