关于DBContext的接口的良好做法

关于DBContext的接口的良好做法

本文介绍了实体框架核心3:关于DBContext的接口的良好做法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Entity Framework Core 3.1中在DBContext上创建接口是一种好习惯吗?微软对此有任何文档吗?

Is creating an Interface on DBContext good practice in Entity Framework Core 3.1? Does Microsoft have any documentation on this?

我们知道在单元测试中模拟DBContext是不好的做法,但是如何在其上创建接口呢?

We know that Mocking DBContext in Unit testing is bad practice, however how about creating an Interface over it?

https://docs.microsoft.com/en-us/ef/core/testing/

资源:为什么DbContext不实现IDbContext接口?

推荐答案

如果您的目标是促进与DbContext交互的单元测试代码,那么我建议您与工作单元一起管理Rebory模式来管理DbContext生命周期范围和提交.我已经概述了在各种答案中实现灵活且易于测试的存储库类的有效方法,但这可能是最好的总结:()

If your objective is to facilitate unit testing code that interacts with the DbContext then I would recommend looking at implementing the Repository pattern alongside a Unit of Work to manage the DbContext lifetime scope and commits. I have outlined effective ways to implement flexible, and easily test-able repository classes in various answers, but this one probably sums it up best: (How to set multiple services from Entity Framework Core on Repository Pattern?)

我建议避免使用通用存储库,而应该拥抱EF的 IQueryable 支持的功能,以构建极其简单的模拟层,从而可以提供有效而灵活的查询.

I recommend avoiding generic repository implementations and embracing the power of EF's IQueryable support to build an extremely simple layer to mock that can provide efficient and flexible querying.

最后一个细节是,如果您确实想支持通过存储库进行 async 查询并要对其进行单元测试,可以在此处找到支持此操作的宝贵技巧:()

The last detail is if you do want to support async querying through the repository and want to unit test those, an invaluable tip to support this can be found here: (Unit-testing .ToListAsync() using an in-memory)

这篇关于实体框架核心3:关于DBContext的接口的良好做法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 03:19