Entity Framework 4.1 Automatic Date

I am new to Entity Framework (and asp.net mvc 3) and this is my first experience with EF4.1 code.

My question is simple: when I generate a new table for the database through the model, I would like to do

  • Automatically add the current datetime to the field when creating a new row.
  • Automatic field update every time the field is updated.

Actually, the variable looks like:

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

I think I could write something in the "OnModelCreating" event for the datacontext, but I'm too new to handle it already :)

Can anyone help?

thanks in advance, V.

+5
source share
2 answers

. "" - . OnModelCreating , . .

, 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();
}
+10

, ?

private DateTime _dateOfRequest = DateTime.Today;
   [Display(Name = "Date of Request"), DataType(DataType.Date)]
   public System.DateTime DateOfRequest {
        get { return _dateOfRequest; }
        set { _dateOfRequest = value; }
   }
0

All Articles