HowTo update every row with unique value on migration using entity framework code first implementation

Viewed 4772

I am looking for an appropriate way to expand an existing database, based on entity framework 6 code first implementation, and adding unique values to the new field for every existing row in the table.

So far I have created a migration wich adds the new field.

The Up method looks like this:

Public Overrides Sub Up()
    AddColumn("dbo.Customers", "UniqueCode", Function(c) c.String(unicode:=False))
End Sub

I am stuck at the point where the new field should be filled with a unique (calculated) value. To keep it simple, let's say every existing row in the database should be assigned a GUID upon the migration.

Using an SQL statement like this would update all rows with the same GUID. But I need it to be unique for every row.

Sql("Update dbo.Customers SET UniqueCode = '" & Guid.NewGuid().ToString)

Using a foreach in the Up method seems kinda wrong... What is best practice in this case?

In addition: The database I am using is access, so I can't use newid() or random(). The GUID is meant to be a dummy for a programmatically calculated value. It will be a hashed value of some other attributes of the customer. So it must be calculated and updated with migration.

2 Answers
Related