我在我的网站上使用EF和ASP.NET MVC。数据库中的所有表都有两个字段
LastModifiedBy - 登录用户名
LastModifiedDate - 今天的日期和时间
我可以在一个地方编写一些代码,这些代码会在创建或更新行时将这些值输入到表中吗?
答案 0 :(得分:0)
尝试覆盖数据上下文中的ValidateEntity方法。以下是一个例子:
public partial class YourDataContext
{
protected override System.Data.Entity.Validation.DbEntityValidationResult ValidateEntity(System.Data.Entity.Infrastructure.DbEntityEntry entityEntry, IDictionary<object, object> items)
{
if (entityEntry.Entity is Boat && entityEntry.State == System.Data.Entity.EntityState.Modified)
{
Boat modifiedBoat = (Boat)entityEntry.Entity;
// Set your last modified date and other properties here
}
return base.ValidateEntity(entityEntry, items);
}
}
答案 1 :(得分:0)
我就是这样做的。首先创建一个具有用户和时间所需属性的接口:
public interface IAudit
{
DateTime? UpdatedOn { get; set; }
int? UpdatedBy { get; set; }
}
确保需要这些属性的任何实体都在实现它:
public class Car : IAudit
{
//snip
public DateTime? UpdatedOn { get; set; }
public int? UpdatedBy { get; set; }
}
现在在你的背景下:
public class MyContext : DbContext
{
public MyContext()
{
//Handle the SavingChanges event:
var objectContext = ((IObjectContextAdapter)this).ObjectContext;
objectContext.SavingChanges += objectContext_SavingChanges;
}
private void objectContext_SavingChanges(object sender, EventArgs e)
{
var context = (ObjectContext)sender;
context.DetectChanges();
foreach (var entry in context.ObjectStateManager
.GetObjectStateEntries(EntityState.Added | EntityState.Modified))
{
if (entry.Entity is IAudit)
{
if (entry.IsRelationship) continue;
var auditEntry = (IAudit)entry.Entity;
if (entry.State == EntityState.Modified)
{
auditEntry.UpdatedOn = DateTime.Now;
auditEntry.UpdatedBy = GetUser();
}
}
}
}
}