Net Core:修改DBSet时运行DBContext重写功能 [英] Net Core: DBContext Override to run functionality when DBSet is modified

查看:385
本文介绍了Net Core:修改DBSet时运行DBContext重写功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在以下情况下是否存在方法:用任何方式修改了ProductType Dbset,
(插入,更新,删除等)控制台写入Hello。



最终,团队希望附加其他复杂的功能。我希望在编译时通过重写来实现这一点,而不是在运行时进行跟踪等。

 公共类CustomStoreContext:StoreContext 
{
public CustomContext()
{
}

public DbSet< Product>
{
console.WriteLine( Hello);
}
}

}



我们是否必须重写所有DBSet修改功能,还是有更简单的方法?
*还需要考虑添加实体图。
我们正在使用EF Net Core 2.2

解决方案

您可以覆盖SaveChanges()并检查您感兴趣的任何实体是否受到影响:在EFCore中对SaveChanges进行回调?



如果您正在寻找解决方案,当条目更改但在将它们保存到数据库之前(例如,调用 Products.Add()之前)执行一些代码,您可以将代码库重构为存储库模式。这样一来,您便可以在上下文之上附加一层内容,在其中您可以执行所需的任何操作。


Is there a method when: ProductType Dbset is modified in any way, (insert, update, delete, etc) Console writes Hello.

Eventually team wants to append other intricate functionality. I want this in compilation time through overriding, Not execution run time with tracking, etc.

public class CustomStoreContext : StoreContext
{
    public CustomContext()
    {
    }

    public DbSet<Product>
    {
        console.WriteLine("Hello");
    }
}

}

Do we have to override all DBSet modification functionalities, or is there easier way? * Also need to account for Add Entity Graph .https://www.entityframeworktutorial.net/entityframework5/add-entity-graph-using-dbcontext.aspx

Would not like not be on SaveChanges, since only looking for few Entities. Condition on SaveChanges can affect mass performance.

We are using EF Net Core 2.2

解决方案

You can override SaveChanges() and check if any entities that you are interested in are affected: Callback on SaveChanges in EFCore?.

If you are looking for a solution to execute some code when entries are changed but before they are saved to the DB (when you call Products.Add() for example), they you can refactor your codebase to Repository pattern. That gives you additional layer on top of context where you can do whatever you need.

这篇关于Net Core:修改DBSet时运行DBContext重写功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆