[英]How should custom code be run during an Entity Framework database migration?
I have a very simple Entity Framework 5 DbMigration that is adding a new boolean column to an existing table with thousands of records in it. 我有一个非常简单的Entity Framework 5 DbMigration,它向具有数千条记录的现有表中添加了一个新的布尔列。 I want the initial value of that column for each existing row to be set based on the value in two other columns in the same table.
我希望基于同一表中其他两个列中的值来设置每个现有行的该列的初始值。 This should only affect existing records, therefore should only be run when the migration is performed and never run again.
这只会影响现有记录,因此仅应在执行迁移时运行,而不再运行。
This is basically the logic that needs to be executed: 这基本上是需要执行的逻辑:
var users = (from u in context.Users select u).ToList();
users.ForEach(u =>
{
u.MyNewBoolColumn = (u.Column1 != null && u.Column2 == "some-value");
context.Users.AddOrUpdate(u);
});
There are two options I can think of, but I don't like either of them: 我可以想到两种选择,但我都不喜欢其中一种:
Is there another, better option? 还有其他更好的选择吗?
A migration represents a change in the schema
, therefor you can't use AddOrUpdate() stuff inside a migration. 迁移表示
schema
的更改,因此您不能在迁移内使用AddOrUpdate()东西。 But you can, and this is what I would suggest you, run plain SQL code using the Sql()
method. 但是可以,并且这就是我建议您使用
Sql()
方法运行纯SQL代码的方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.