Reputation: 687
Basically, in my EF database I have added a DateTime row to my table using EF code first.
Here's how it is now:
public class Employee
{
[Key]
public int Id { get; set; }
public DateTime Date { get; set; } //this has been added
}
As you see the Date is not nullable - therefore I need to initially populate the dates when I run the migration.
Here's the generated migration script:
public partial class Changed_Employee : DbMigration
{
public override void Up()
{
AddColumn("dbo.Employees", "Date", c => c.DateTime(nullable: false));
}
}
The thing is, I would like to run some custom C# logic in order to determine the exact date of each individual "Employee".
However, how would I do this?
Upvotes: 1
Views: 767
Reputation: 17043
The easiest way to do that:
During the migration set all date/time to 00.00.0000
Sql("UPDATE Employees SET Date= -DATEDIFF(MINUTE, CurrentTime, 0)";
When the application started you can create a custom seed method which use C# to update the data:
Pros: Very easy
Cons: When you have multipe migration levels, you will lose some migration logic(Date time transformation). The data will be transformed later by app starting.
By the way maybe also you need to set the column Date as nullable and fill it with data and then at the end of the script alter the table and change the column to nullable, otherwise the migration will not working.
AddColumn("dbo.Employees", "Date", c => c.DateTime(nullable: true));
..
..
..
Sql("Update....")
..
..
AlterColumn("dbo.Employees", "Date", c => c.DateTime(nullable: false));
For the different approaches you have to read my post here: Read database during an entity framework migration (select query)
Upvotes: 2