How to add computed column using migrations in code first?

旧街凉风 提交于 2019-12-08 01:40:50

问题


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)


回答1:


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


来源:https://stackoverflow.com/questions/42529883/how-to-add-computed-column-using-migrations-in-code-first

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!