简体   繁体   English

实体框架迁移 - 添加具有现有条目值的新列

[英]Entity framework migration - add new column with a value for existing entries

I have an application with Entity Framework Code First. 我有一个Entity Framework Code First的应用程序。

In a table, I have to add a column. 在表格中,我必须添加一列。 So I added it in the model and created a Migration. 所以我在模型中添加了它并创建了一个Migration。

But during the migration, I would like to update the existing entries and add a value for this new column. 但是在迁移期间,我想更新现有条目并为此新列添加值。 This value has to be taken from the database (a constant field in my "Configuration" table). 该值必须从数据库中获取(我的“配置”表中的常量字段)。

But the default value should only be applied for existing entries, not for the next. 但默认值应仅适用于现有条目,而不适用于下一条目。

How can I do it from my Migration class ? 我怎么能从我的Migration类中做到这一点?

My current migration class : 我目前的迁移类:

public override void Up()
{
    var theDefaultValue = MyConstants.MyConstantParameterFromDatabase;
    AddColumn("MySchema.MyTable", "MyNewColumn", c => c.Decimal(nullable: false, precision: 18, scale: 2));
}

Edit : still looking for a solution to update all existing entries (with 0 value) but only after this migration... 编辑:仍然在寻找更新所有现有条目(具有0值)的解决方案,但仅在此迁移之后...

You simply have to modify the Up() method, and include in it a SQL statement to set the column value in the existing rows. 您只需修改Up()方法,并在其中包含一个SQL语句来设置现有行中的列值。 This will only be executed when the database is updated, and the update involves this particular Migration. 这仅在更新数据库时执行,并且更新涉及此特定迁移。 Thus only the already existing rows will be updated when the Update-Database is invoked. 因此,在调用Update-Database时,只会更新现有的行。

Add code like this after the AddColumn command, so that the column is already available in the table when the SQL statement runs: AddColumn命令之后添加这样的代码,以便在SQL语句运行时该列已在表中可用:

Sql("UPDATE dbo.MyTable SET Column = (SELECT val FROM config)");

NOTE: (SELECT val FROM config) is pseudocode that you must replace with a query that returns the desired value 注意: (SELECT val FROM config)是伪代码,您必须使用返回所需值的查询替换该伪代码

I wanted to copy a value from an existing column and inset to the newly introduced column in my Postgresql database, while running the update-database . 我想在运行update-database将现有列和插入的值复制到Postgresql数据库中新引入的列。 So I edited the Up function in the Migration class. 所以我在Migration类中编辑了Up函数。

protected override void Up(MigrationBuilder migrationBuilder) {
    migrationBuilder.AddColumn < string > (
    name: "FileName", table: "FavoriteFiles", nullable: false, defaultValue: "");
    migrationBuilder.Sql("UPDATE \"FavoriteFiles\" SET \"FileName\" = SPLIT_PART(\"FilePath\", '/', 7) WHERE \"FilePath\" IS NOT NULL;");
}

Then I ran Update-Database . 然后我运行了Update-Database Hope it helps. 希望能帮助到你。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM