打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
Audit Fields Using Entity Framework Code First ? Jonathan Creamer's Dev Diary

Fields Using Entity Framework Code First

One common need among database creation is auditing. Fields likeDateCreated, DateLastUpdated, etc...etc... Well with EF Code First,there is one pretty easy way of getting it accomplished.

EF Code First uses a class that inherits from a DbContext to storeall of the different Entities used in your application. It lookssomething like...

public class MyContext : DbContext{public DbSet<MyEntity> MyEntities { get; set; }}

By overriding the SaveChanges method like this...

public override int SaveChanges(){// var auditUser = HttpContext.Current.User.Identity.Name;DateTime auditDate = DateTime.UtcNow;foreach (DbEntityEntry<IAuditable> entry in ChangeTracker.Entries<IAuditable>()){if (entry.State == EntityState.Added){entry.Entity.CreatedOn = auditDate;entry.Entity.ModifiedOn = auditDate;// entry.Entity.CreatedBy = auditUser;// entry.Entity.ModifiedBy = auditUser;}else if (entry.State == EntityState.Modified){entry.Entity.ModifiedOn = auditDate;// entry.Entity.ModifiedBy = auditUser;}}return base.SaveChanges();}

You can uncomment the two user fields and update the user with this code as well.

本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
EF架构~关系表插入应该写在事务里,但不应该是分布式事务
谈ENTITYFRAMEWORK数据更新之技巧
vba对word中域的直接操作
Entity Framework中的批量提交与分布式事务处理
Spring Data JPA
ORM框架EF(一)增删改查
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服