EntityFrameworkã§ã³ã¼ããã¡ã¼ã¹ããã¦ãæã®è©±ã§ãã
æ¥åã¢ããªçã§ã¯ãã¼ã¿ããã¤ç»é²ãæ´æ°ãããã®ããæãããããã¾ãããã
ã¨ã³ãã£ãã£ã¯ã©ã¹ã«ç»é²æ¥æãæ´æ°æ¥æãªãã¦ã¡ã³ãã¼ãæããããã®ã®ãããããã¡ãã¡ãã¸ãã¹ãã¸ãã¯ã®ä¸ã§æ´æ°ããã®ã¯è¶ ããã©ãããããªããããæ¹æ³ãªããããªã¼ã¨èª¿ã¹ã¦ããããä¸è¨ãµã¤ãã«ããæ¹æ³ãè¼ã£ã¦ã¾ããã
ããã¯ã¡ãã£ã¨æå¿ãã¾ãã*1ã
DbContextã®æ´¾çã¯ã©ã¹ã§SaveChangesã¡ã½ããããªã¼ãã¼ã©ã¤ã
以ä¸ã®ã³ã¼ãã§ç»é²ã®æã¯CreateDateTimeãUpdateDateTimeã«ã·ã¹ãã æå»ãã»ããããã¾ããä¿®æ£ã®å ´åã¯ãã¡ããUpdateDateTimeã®ã¿ãæ´æ°ãããä»çµã¿ã§ãã
CreateDateTimeãUpdateDateTimeããããã£ããªãã¨ã³ãã£ãã£ã¯ã©ã¹ã¯å¯¾è±¡å¤ã¨ãªãã¾ãã®ã§ä¾å¤ãçºçãã¾ããã
public class AppDbContext:DbContext { public DbSet<School> Schools { get; set; } public DbSet<Category> Categories { get; set; } public override int SaveChanges() { var now = DateTime.Now; SetCreateDateTime(now); SetUpdateDateTime(now); return base.SaveChanges(); } private void SetUpdateDateTime(DateTime now) { var entities = this.ChangeTracker.Entries() .Where(e => (e.State == EntityState.Added || e.State == EntityState.Modified) && e.CurrentValues.PropertyNames.Contains("UpdateDateTime")) .Select(e => e.Entity); foreach (dynamic entity in entities) { entity.UpdateDateTime = now; } } private void SetCreateDateTime(DateTime now) { var entities = this.ChangeTracker.Entries() .Where(e => e.State == EntityState.Added && e.CurrentValues.PropertyNames.Contains("CreateDateTime")) .Select(e => e.Entity); foreach (dynamic entity in entities) { entity.CreateDateTime = now; } } }
dynamicãæ´»ãã¦ã¾ããããã°ãããã
ãããå¿ç¨ããã°ããããã§ãã¾ãã*2ã