Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EF 4.1 - How to add a default on insertion for datetime column

Using EF 4.1 how could I add a default value to the underlying table? In this particular case how could I set a datetime column to the equivalent of getdate every time I insert a new record to the database, without having to set it in code.

Thanks in advance

like image 504
andyJ Avatar asked Jan 19 '23 14:01

andyJ


2 Answers

The solution proposed by @elkdanger is way to go but just if you use code-first approach you don't have to create partial class - you can place initialization directly to your entity.

Don't use database approach! It will not work because it would demand marking property as database generated (to be correctly repopulated after insert). Once you mark property database generated you can never change its value in the application.

The last option is overriding SaveChanges in your derived DbContext and setting the property manually. Something like:

public override int SaveChanges()
{
    var entities = ChangeTracker.Entries<YourEntityType>()
                                .Where(e => e.State == EntityState.Added)
                                .Select(e => e.Entity);
    var currentDate = DateTime.Now;
    foreach(var entity in entities)
    {
        entity.Date = currentDate;
    }

    return base.SaveChanges();
}

This approach can be better if there can be significant difference between creating an instance of the entity and saving the instanance.

like image 51
Ladislav Mrnka Avatar answered May 08 '23 03:05

Ladislav Mrnka


You could create a partial class for your entity, and inside the constructor set the date column to DateTime.Now. This way, every time you create an instance of your class, that field will be set to the current date "automatically".

like image 43
Steve Hobbs Avatar answered May 08 '23 02:05

Steve Hobbs