在我的mvc应用程序中,我有一个基本模型如下
namespace ModulericaV1.Models
{
public class BaseModel
{
private ApplicationDbContext db = new ApplicationDbContext();
public DateTime? CrDate { get; set; }
[ForeignKey("CrUser")]
public ApplicationUser UserCr { get; set; }
public string CrUser { get; set; }
public DateTime? MdDate { get; set; }
[ForeignKey("MdUser")]
public ApplicationUser UserMd { get; set; }
public string MdUser { get; set; }
public bool IsDeleted { get; set; }
public ApplicationUser GetUserObject(string id)
{
var UserObject = db.Users.Find(id);
return UserObject;
}
public void LogBasic()
{
if (this.CrDate == null)
{
this.CrDate = System.DateTime.Now;
this.CrUser = HttpContext.Current.User.Identity.GetUserId();
}
else
{
this.MdDate = System.DateTime.Now;
this.MdUser = HttpContext.Current.User.Identity.GetUserId();
}
}
}
}
我的所有模型都继承了:BaseModel。我正在尝试做什么,为所有创建和更新数据库查询调用LogBasic()方法,以便我可以记录哪个用户创建新行或进行更改。
我应该在哪里调用LogBasic()方法。
答案 0 :(得分:0)
可能这样的事情应该有效:
public class ApplicationDbContext : DbContext {
// ...
public override int SaveChanges () {
if(HasChanges()){
foreach(var entry in Entries<BaseModel>()){
((BaseModel)entry.Entity).LogBasic();
}
}
}
// ...
}
答案 1 :(得分:0)
执行此操作的最佳位置是ApplicationDbContext
方法的SaveChanges()
。您可以遍历所有待处理更新的项目,如果它们是BaseModel
,请记录它们。
我没有准确的语法,但这就是这个想法:
public class ApplicationDbContext : DbContext
{
//.....
public override int SaveChanges()
{
foreach(var entity in this.ChangeTracker.Entries)
{
var baseModel = entity as BaseModel;
if(baseModel!=null)
{
switch(entity.State)
{
case State.Modified;
// Do things with an updated version
case State.Deleted:
// Do things with the deleted version
case State.Added:
{
// Do things with the Added entity
baseModel.LogBasic();
break;
}
}
}
base.SaveChanges();
}
}