EFCore 5 新特性 `SaveChangesInterceptor`
EFCore 5 新特性 SaveChangesInterceptor
Intro
之前 EF Core 5 还没正式发布的时候有发布过一篇关于 SaveChangesEvents 的文章,有需要看可以移步到 efcore 新特性 SaveChanges Events,在后面的版本中又加入了 Interceptor 的支持,可以更方便的实现 SaveChanges 事件的复用, 今天主要介绍一下通过 SaveChangesInterceptor 来实现日志审计
SaveChangesInterceptor
源码实现:
public interface ISaveChangesInterceptor : IInterceptor
{
/// <summary>
/// Called at the start of <see cref="M:DbContext.SaveChanges" />.
/// </summary>
/// <param name="eventData"> Contextual information about the <see cref="DbContext" /> being used. </param>
/// <param name="result">
/// Represents the current result if one exists.
/// This value will have <see cref="InterceptionResult{Int32}.HasResult" /> set to <see langword="true" /> if some previous
/// interceptor suppressed execution by calling <see cref="InterceptionResult{Int32}.SuppressWithResult" />.
/// This value is typically used as the return value for the implementation of this method.
/// </param>
/// <returns>
/// If <see cref="InterceptionResult{Int32}.HasResult" /> is false, the EF will continue as normal.
/// If <see cref="InterceptionResult{Int32}.HasResult" /> is true, then EF will suppress the operation it
/// was about to perform and use <see cref="InterceptionResult{Int32}.Result" /> instead.
/// A normal implementation of this method for any interceptor that is not attempting to change the result
/// is to return the <paramref name="result" /> value passed in.
/// </returns>
InterceptionResult<int> SavingChanges(
[NotNull] DbContextEventData eventData,
InterceptionResult<int> result);
/// <summary>
/// <para>
/// Called at the end of <see cref="M:DbContext.SaveChanges" />.
/// </para>
/// <para>
/// This method is still called if an interceptor suppressed creation of a command in <see cref="SavingChanges" />.
/// In this case, <paramref name="result" /> is the result returned by <see cref="SavingChanges" />.
/// </para>
/// </summary>
/// <param name="eventData"> Contextual information about the <see cref="DbContext" /> being used. </param>
/// <param name="result">
/// The result of the call to <see cref="M:DbContext.SaveChanges" />.
/// This value is typically used as the return value for the implementation of this method.
/// </param>
/// <returns>
/// The result that EF will use.
/// A normal implementation of this method for any interceptor that is not attempting to change the result
/// is to return the <paramref name="result" /> value passed in.
/// </returns>
int SavedChanges(
[NotNull] SaveChangesCompletedEventData eventData,
int result);
/// <summary>
/// Called when an exception has been thrown in <see cref="M:DbContext.SaveChanges" />.
/// </summary>
/// <param name="eventData"> Contextual information about the failure. </param>
void SaveChangesFailed(
[NotNull] DbContextErrorEventData eventData);
/// <summary>
/// Called at the start of <see cref="M:DbContext.SaveChangesAsync" />.
/// </summary>
/// <param name="eventData"> Contextual information about the <see cref="DbContext" /> being used. </param>
/// <param name="result">
/// Represents the current result if one exists.
/// This value will have <see cref="InterceptionResult{Int32}.HasResult" /> set to <see langword="true" /> if some previous
/// interceptor suppressed execution by calling <see cref="InterceptionResult{Int32}.SuppressWithResult" />.
/// This value is typically used as the return value for the implementation of this method.
/// </param>
/// <param name="cancellationToken"> The cancellation token. </param>
/// <returns>
/// If <see cref="InterceptionResult{Int32}.HasResult" /> is false, the EF will continue as normal.
/// If <see cref="InterceptionResult{Int32}.HasResult" /> is true, then EF will suppress the operation it
/// was about to perform and use <see cref="InterceptionResult{Int32}.Result" /> instead.
/// A normal implementation of this method for any interceptor that is not attempting to change the result
/// is to return the <paramref name="result" /> value passed in.
/// </returns>
ValueTask<InterceptionResult<int>> SavingChangesAsync(
[NotNull] DbContextEventData eventData,
InterceptionResult<int> result,
CancellationToken cancellationToken = default);
/// <summary>
/// <para>
/// Called at the end of <see cref="M:DbContext.SaveChangesAsync" />.
/// </para>
/// <para>
/// This method is still called if an interceptor suppressed creation of a command in <see cref="SavingChangesAsync" />.
/// In this case, <paramref name="result" /> is the result returned by <see cref="SavingChangesAsync" />.
/// </para>
/// </summary>
/// <param name="eventData"> Contextual information about the <see cref="DbContext" /> being used. </param>
/// <param name="result">
/// The result of the call to <see cref="M:DbContext.SaveChangesAsync" />.
/// This value is typically used as the return value for the implementation of this method.
/// </param>
/// <param name="cancellationToken"> The cancellation token. </param>
/// <returns>
/// The result that EF will use.
/// A normal implementation of this method for any interceptor that is not attempting to change the result
/// is to return the <paramref name="result" /> value passed in.
/// </returns>
ValueTask<int> SavedChangesAsync(
[NotNull] SaveChangesCompletedEventData eventData,
int result,
CancellationToken cancellationToken = default);
/// <summary>
/// Called when an exception has been thrown in <see cref="M:DbContext.SaveChangesAsync" />.
/// </summary>
/// <param name="eventData"> Contextual information about the failure. </param>
/// <param name="cancellationToken"> The cancellation token. </param>
/// <returns> A <see cref="Task" /> representing the asynchronous operation. </returns>
Task SaveChangesFailedAsync(
[NotNull] DbContextErrorEventData eventData,
CancellationToken cancellationToken = default);
}
为了比较方便的实现自己需要的 Interceptor,微软还提供了一个 SaveChangesInterceptor 抽象类,这样只需要继承于这个类,重写自己需要的方法即可,实现比较简单,就是实现了 ISaveChangesInterceptor 接口,然后接口的实现都是空的虚方法
源码链接:https://github.com/dotnet/efcore/blob/v5.0.0/src/EFCore/Diagnostics/SaveChangesInterceptor.cs
使用 SaveChangesInterceptor 实现自动审计
简单写了一个测试的审计拦截器
public class AuditInterceptor : SaveChangesInterceptor
{
public override InterceptionResult<int> SavingChanges(DbContextEventData eventData, InterceptionResult<int> result)
{
var changesList = new List<CompareModel>();
foreach (var entry in
eventData.Context.ChangeTracker.Entries<Post>())
{
if (entry.State == EntityState.Added)
{
changesList.Add(new CompareModel()
{
OriginalValue = null,
NewValue = entry.CurrentValues.ToObject(),
});
}
else if (entry.State == EntityState.Deleted)
{
changesList.Add(new CompareModel()
{
OriginalValue = entry.OriginalValues.ToObject(),
NewValue = null,
});
}
else if (entry.State == EntityState.Modified)
{
changesList.Add(new CompareModel()
{
OriginalValue = entry.OriginalValues.ToObject(),
NewValue = entry.CurrentValues.ToObject(),
});
}
Console.WriteLine($"change list:{changesList.ToJson()}");
}
return base.SavingChanges(eventData, result);
}
public override int SavedChanges(SaveChangesCompletedEventData eventData, int result)
{
Console.WriteLine($"changes:{eventData.EntitiesSavedCount}");
return base.SavedChanges(eventData, result);
}
private class CompareModel
{
public object OriginalValue { get; set; }
public object NewValue { get; set; }
}
}
实际应用的话还需要根据自己的场景做一些修改和测试
测试 DbContext 示例,这里使用了一个简单的 InMemory 做了一个测试:
public class TestDbContext : DbContext
{
public TestDbContext(DbContextOptions<TestDbContext> dbContextOptions) : base(dbContextOptions)
{
}
public DbSet<Post> Posts { get; set; }
}
public class Post
{
[Key]
public int Id { get; set; }
public string Author { get; set; }
public string Title { get; set; }
public DateTime PostedAt { get; set; }
}
测试代码:
var services = new ServiceCollection();
services.AddDbContext<TestDbContext>(options =>
{
options.UseInMemoryDatabase("Tests")
//.LogTo(Console.WriteLine) // EF Core 5 中新的更简洁的日志记录方式
.AddInterceptors(new AuditInterceptor())
;
});
using var provider = services.BuildServiceProvider();
using (var scope = provider.CreateScope())
{
var dbContext = scope.ServiceProvider.GetRequiredService<TestDbContext>();
dbContext.Posts.Add(new Post() { Id = 1, Author = "test", Title = "test", PostedAt = DateTime.UtcNow });
dbContext.SaveChanges();
var post = dbContext.Posts.Find(1);
post.Author = "test2";
dbContext.SaveChanges();
dbContext.Posts.Remove(post);
dbContext.SaveChanges();
}
输出结果(输出结果的如果数据为 null 就会被忽略掉,所以对于新增的数据实际是没有原始值的,对于删除的数据没有新的值):
More
EF Core 5 还有很多新的特性,有需要的小伙伴可以看一下官方文档的介绍~
上述源码可以在 Github 上获取 https://github.com/WeihanLi/SamplesInPractice/blob/master/EF5Samples/SaveChangesInterceptorTest.cs
Reference
- https://github.com/dotnet/efcore
- https://docs.microsoft.com/en-us/ef/core/what-is-new/ef-core-5.0/whatsnew#savechanges-interception-and-events
- https://www.cnblogs.com/weihanli/p/13416219.html
- https://github.com/WeihanLi/SamplesInPractice/blob/master/EF5Samples/SaveChangesInterceptorTest.cs
EFCore 5 新特性 `SaveChangesInterceptor`的更多相关文章
- EFCore 5 新特性 —— Savepoints
EFCore 5 中的 Savepoints Intro EFCore 5中引入了一个新特性,叫做 Savepoints,主要是事务中使用,个人感觉有点类似于 Windows 上的系统还原点,如果事务 ...
- efcore 新特性 SaveChanges Events
efcore 新特性 SaveChanges Events Intro 昨天早上看到之前关注的一个 efcore 的 issue 被 closed ,于是看了一眼, ef core 新合并了一个 PR ...
- SQL Server 2014 新特性——内存数据库
SQL Server 2014 新特性——内存数据库 目录 SQL Server 2014 新特性——内存数据库 简介: 设计目的和原因: 专业名词 In-Memory OLTP不同之处 内存优化表 ...
- ElasticSearch 5学习(10)——结构化查询(包括新特性)
之前我们所有的查询都属于命令行查询,但是不利于复杂的查询,而且一般在项目开发中不使用命令行查询方式,只有在调试测试时使用简单命令行查询,但是,如果想要善用搜索,我们必须使用请求体查询(request ...
- [干货来袭]C#6.0新特性
微软昨天发布了新的VS 2015 ..随之而来的还有很多很多东西... .NET新版本 ASP.NET新版本...等等..太多..实在没消化.. 分享一下也是昨天发布的新的C#6.0的部分新特性吧.. ...
- CSS3新特性应用之结构与布局
一.自适应内部元素 利用width的新特性min-content实现 width新特性值介绍: fill-available,自动填充盒子模型中剩余的宽度,包含margin.padding.borde ...
- 【译】Meteor 新手教程:在排行榜上添加新特性
原文:http://danneu.com/posts/6-meteor-tutorial-for-fellow-noobs-adding-features-to-the-leaderboard-dem ...
- 跨平台的 .NET 运行环境 Mono 3.2 新特性
Mono 3.2 发布了,对 Mono 3.0 和 2.10 版本的支持不再继续,而且这两个分支也不再提供 bug 修复更新. Mono 3.2 主要新特性: LLVM 更新到 3.2 版本,带来更多 ...
- Atitit opencv版本新特性attilax总结
Atitit opencv版本新特性attilax总结 1.1. :OpenCV 3.0 发布,史上功能最全,速度最快的版1 1.2. 应用领域2 1.3. OPENCV2.4.3改进 2.4.2就有 ...
随机推荐
- python之线程池和进程池
线程池和进程池 一.池的概念 池是用来保证计算机硬件安全的情况下最大限度的利用计算机 它降低了程序的运行效率但是保证了计算机硬件的安全从而让你写的程序能够正常运行 ''' 无论是开设进程也好还是开设线 ...
- java 的 callback
Java 本身没有回调这一说,但是面向对象可以模拟出来. 1. 回调接口对象 ICommand package com.git.Cmder; public interface ICommand { v ...
- ZooKeeper伪分布式集群安装及使用
ZooKeeper伪分布式集群安装及使用 让Hadoop跑在云端系列文章,介绍了如何整合虚拟化和Hadoop,让Hadoop集群跑在VPS虚拟主机上,通过云向用户提供存储和计算的服务. 现在硬件越来越 ...
- MeteoInfoLab脚本示例:MERRA HDF数据
MERRA是NOAA的一种再分析资料,HDF数据遵循COARDS协议,读取比较简单.脚本程序: #Add data file folder = 'D:/Temp/hdf/' fns = 'MERRA3 ...
- pytest文档46-关于https请求警告问题(InsecureRequestWarning: Unverified HTTPS request is being made)
前言 使用 pytest 执行 https 请求用例的时候,控制台会出现警告:InsecureRequestWarning: Unverified HTTPS request is being mad ...
- 【数论】HDU 4143 A Simple Problem
题目内容 给出一个正整数\(n\),找到最小的正整数\(x\),使之能找到一个整数\(y\),满足\(y^2=n+x^2\). 输入格式 第一行是数据组数\(T\),每组数据有一个整数\(n\). 输 ...
- BOOST库 消息队列
直接贴实验代码: /******* boost 消息队列 **********/ #if 1 #include <boost/thread/thread.hpp> #include < ...
- python matplotlib配置
import matplotlib.pyplot as plt import matplotlib as mpl from matplotlib.font_manager import FontPro ...
- if else 太多?看我用 Java 8 轻松干掉!
之前我用 Java 8 写了一段逻辑,就是类似下面这样的例子: /* * 来源公众号:Java技术栈 */ if(xxxOrder != null){ if(xxxOrder.getXxxShippi ...
- java数据结构-12树相关概念
一.树 1.概念: 包含n(n>=0)个结点的有穷集:树有多个节点(node),用以储存元素.某些节点之间存在一定的关系,用连线表示,连线称为边(edge).边的上端节点称为父节点,下端称为子节 ...