简体   繁体   English

Entity Framework Core 中实体的拦截保存

[英]Intercept saving of entities in Entity Framework Core

Is there a way for EF Core to intercept the pre insertion, pre update, pre delete, post insert, post update and post delete events of an entity? EF Core 有没有办法拦截实体的预插入、预更新、预删除、插入后、更新后和删除后事件?

EF core supports interceptors, but I think it's more focused on logging queries https://www.entityframeworktutorial.net/entityframework6/database-command-interception.aspx EF 核心支持拦截器,但我认为它更侧重于记录查询https://www.entityframeworktutorial.net/entityframework6/database-command-interception.aspx

I'm looking for a feature like this https://github.com/khellang/EF.Interception我正在寻找这样的功能https://github.com/khellang/EF.Interception

You already have a class that extends DbContext .您已经有一个扩展DbContext的类。 Override the SaveChanges methods and you can examine the contents of the ChangeTracker to handle all your pre- event needs;覆盖SaveChanges方法,您可以检查ChangeTracker的内容来处理您的所有事件前需求;

        private void PreSave()
        {
            foreach (var entry in ChangeTracker.Entries())
            {
                switch (entry.State)
                {...}
            }
        }

        public override async Task<int> SaveChangesAsync(bool acceptAllChangesOnSuccess, CancellationToken cancellationToken = default(CancellationToken))
        {
            PreSave();
            return await base.SaveChangesAsync(acceptAllChangesOnSuccess, cancellationToken);
        }

        public override int SaveChanges(bool accept) {
            PreSave();
            return base.SaveChanges(accept);
        }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM