Entity Framework 4.1 Automatic date

天大地大妈咪最大 提交于 2019-12-21 05:06:25

问题


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.


回答1:


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



回答2:


Why not define the property to be one with a backing field, which is initialized to the default value ?

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


来源:https://stackoverflow.com/questions/6465438/entity-framework-4-1-automatic-date

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!