如何首先使用代码中的迁移添加计算列? [英] How to add computed column using migrations in code first?

查看:74
本文介绍了如何首先使用代码中的迁移添加计算列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已将此计算列添加到我的数据模型中

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])

运行代码时,我得到一个错误,提示我数据库已更改。
我的问题如何为该计算列创建迁移(因为它已经使用sql查询创建了)

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)

推荐答案

实体框架不知道如何正确处理计算列的迁移,因此您需要提供帮助。

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

替换 Up()

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

这篇关于如何首先使用代码中的迁移添加计算列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆