0

我首先在我的 asp.net mvc 项目中使用 EF 代码。我想在每个表中都有一个 updated_at(DateTime) 列。因此,如果我更新一条记录,我希望将列值设置为当前 DateTime。

public abstract class User
{
    [Key]
    [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
    public int UserId { get; set; }
    [Required]
    public string name { get; set; }
    [Required]
    public string email { get; set; }
    [Required]
    public string password { get; set; }

    private DateTime _created_at;
    private DateTime _updated_at;

    public User()
    {
        _created_at = DateTime.Now;
        _updated_at = DateTime.Now;
    }

    public virtual DateTime created_at
    {
        get
        {
            return this._created_at;
        }
    }

    public virtual DateTime updated_at
    {
        get
        {
            return this._updated_at;
        }
    }
}

如何在不直接在数据库中编写触发器的情况下在 EF 中实现这一点。

4

2 回答 2

3

在您DbContext的构造函数中使用以下内容:

public MyDbContext()
{
    ((IObjectContextAdapter)this).ObjectContext.SavingChanges += ObjectContext_SavingChanges;
}

void ObjectContext_SavingChanges(object sender, EventArgs e)
{
    // Ensure that we are passed an ObjectContext
    ObjectContext context = sender as ObjectContext;
    if (context != null)
    {
        // Set DateTime to UTC when
        foreach (ObjectStateEntry entry in
            context.ObjectStateManager.GetObjectStateEntries(
            EntityState.Modified))
        {
            if (entry.Entity.GetType().GetProperty("_updated_at") != null)
            {
                dynamic entity = entry.Entity;
                entity._updated_at = DateTime.UtcNow;
                DateTime.SpecifyKind(entity._updated_at, DateTimeKind.Utc);
            }
        }
    }
}
于 2013-08-04T20:38:34.273 回答
0

您应该使用一个接口来定义您希望如何处理类中的时间戳信息。您可以将相同的技术用于许多不同的事情。

public interface ITimeStampable
{
    DateTime created_at {get; set;}
    DateTime updated_at {get; set;}
}

public class User : ITimeStampable
{
    public User(){ 
        created_at = DateTime.Now;
        updated_at = DateTime.Now;
    }
    public DateTime created_at {get; set;}
    public DateTime updated_at {get; set;}
}

void ObjectContext_SavingChanges(object sender, EventArgs e)
{
   var context = sender as ObjectContext;

   foreach (ObjectStateEntry entry in
       context.ObjectStateManager.GetObjectStateEntries(
       EntityState.Modified))
   {
       if (typeof(IAuditable).IsAssignableFrom(entry.Entity.GetType()))
                (entity as IAuditable).ChangeTS = DateTime.Now;
   }
}
于 2013-08-05T17:22:50.783 回答