Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework 4.1 Automatic date

i'm quite new to Entity Framework (and asp.net mvc 3) and this is my really first experience with EF4.1 code first.

My question is simple: when I generate via model a new table for database I would like to make

  1. Automatically add current datetime to a field when a new row is created.
  2. Automatically update the field every time the field is updated.

Actually, the variable appears like:

 [DisplayName("Data Modifica")]
 [DataType(DataType.DateTime)]
 [DisplayFormat(DataFormatString = "{0:d}")]
 public DateTime DataModifica { get; set; }

I guess i could write something on "OnModelCreating" event of datacontext but I'm too new to already master this :)

Can someone help?

thanks in advance, V.

like image 483
Valerio Avatar asked Jun 24 '11 08:06

Valerio


1 Answers

That has nothing to do with creation of model. The "model" is description of your mapping between classes and database. OnModelCreating is used to modify mapping definition, not to modify data. It has nothing to do with data in the entity instance itself.

If you want automatic modification you can override SaveChanges:

public override int SaveChanges()
{
     DateTime now = DateTime.Now;
     foreach (var entity in ChangeTracker.Entries<YourEntityType>()
                                         .Where(e => e.State == EntityState.Added || e.State == EntityState.Modified)
                                         .Select(e => e.Entity))
     {
          entity.DateModifica = now; // set the date
     }

     return base.SaveChanges();
}
like image 159
Ladislav Mrnka Avatar answered Sep 28 '22 23:09

Ladislav Mrnka