我首先在我的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;
}
}
}
如果不直接在数据库中编写TRIGGER,我如何在EF中实现这一点。
答案 0 :(得分: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);
}
}
}
}
答案 1 :(得分: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;
}
}