博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

EF SaveChanges重写加入日志

Posted on 2020-05-09 10:45  筑筑  阅读(538)  评论(0编辑  收藏  举报
 public override int SaveChanges()
        {
            var entries = ChangeTracker.Entries().Where(x => x.State != EntityState.Unchanged).GroupBy(x => new { x.State, x.Entity.GetType().Name }).Select(x => new { x.Key.State, x.Key.Name, List = x.ToList() });
            JsonSerializerSettings settings = new JsonSerializerSettings
            {
                ReferenceLoopHandling = ReferenceLoopHandling.Ignore// 发现循环引用时跳过序列化
            };
            foreach (var item in entries)
            {
                        Logger.WriteOperationlog($"\r\n Operation {item.State} Date:{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}\r\n Entity:{item.Name}\r\n Data:{JsonConvert.SerializeObject(item.List.Select(x => x.Entity).ToList(), settings)}", "Default");

            }

            return base.SaveChanges();
        }