Use Entity Framework to Update Column Length and Data in Single Migration Mode

I am using Entity Framework with the first code migrations. I need to increase the length of a VARCHAR(50) column to VARCHAR(100) and update all records in that column by doubling the row. Thus, "abc" turns into "abcabc" (except that the values ​​will be longer than three characters).

It would be nice to be able to do this in the first port of the first code, but I had problems with its operation. First I tried to use this code:

 AlterColumn("dbo.SomeTable", "SomeField", c => c.String(maxLength: 100, unicode: false)); using (TheEntityContext ctx = new TheEntityContext()) { foreach (Entities.SomeTable st in ctx.SomeTables) st.SomeField = st.SomeField + st.SomeField; ctx.SaveChanges(); } 

but I got this error:

A model supporting the "TheEntityContext" context has changed since the database was created. Consider using First First Migrations to update the database ( http://go.microsoft.com/fwlink/?LinkId=238269 ).

I thought it was weird. Maybe I can’t use Entity Framework inside the first code migration? So I tried this code:

 AlterColumn("dbo.SomeTable", "SomeField", c => c.String(maxLength: 100, unicode: false)); using (SqlConnection conn = new SqlConnection(connStr)) { conn.Open(); string sql = "UPDATE SomeTable SET SomeField = SomeField + '' + SomeField"; SqlCommand cmd = new SqlCommand(sql, conn); cmd.ExecuteNonQuery(); } 

but I got this error:

String or binary data will be truncated.

Then I, however, have an ALTER TABLE statement to make the field longer, not valid until the UPDATE ? So I changed the UDPDATE as a string with 50 characters, and it went fine. Running Update-Database -Verbose also indicates that it does not run an ALTER TABLE statement before an UPDATE .

So what's the deal? Should I run ALTER TABLE in one hyphen and then the code to update the table in another?

+7
entity-framework ef-migrations
source share
1 answer

The fact is that EF performs migrations as part of the transaction.

You open a new transaction inside, which is optional, just use

 AlterColumn("dbo.SomeTable", "SomeField", c => c.String(maxLength: 100, unicode: false)); Sql("UPDATE dbo.SomeTable SET SomeField = '' + SomeField + SomeField"); 

In this case, the Sql() function will work in the same transaction context, and the error should not appear.

EDIT : Sql() transaction context explanation.

+13
source share

All Articles