1

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?

1 Answer 1

2

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)

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for your answer. The logic to run is in C# so I guess I could implement it in-between. By the way the "different approaches" you linked to links back to this thread. Could you fix that link please?
Thanks a lot for your answer :) Worked great!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.