Search code examples
entity-frameworkef-code-firstdatabase-migration

How to add computed column using migrations in code first?


I have added this computed column inside my data model

[DatabaseGenerated(DatabaseGeneratedOption.Computed)]
    public string FullName { get; private set; }

After that I created it inside my database using this query

ALTER TABLE [MyDataBase].[dbo].[User] ADD FullName as ([FirstName] + ' ' + [LastName])

When I run my code I get an error that my database has changed . My question How to create migration for this computed column (because it's already created using sql query)


Solution

  • Entity Framework doesn't know how to properly handle migrations for computed columns, so you need to help it out.

    Firstly, delete the computed column from the table in the database.

    Then create a new migration in the package manager console:

    add-migration FullNameComputed
    

    Replace the body of the Up() method in the new migration with the following:

    Sql("ALTER TABLE [TableName] ADD [FullName] AS ([FirstName] + ' ' + [LastName])");
    

    Finally, run the migration from the package manager console:

    update-database