简体   繁体   English

Entity Framework Core 3:DBContext 上的接口好的做法?

[英]Entity Framework Core 3: Interface on DBContext good practice?

Is creating an Interface on DBContext good practice in Entity Framework Core 3.1?在 Entity Framework Core 3.1 中在 DBContext 上创建接口是一种好的做法吗? Does Microsoft have any documentation on this?微软有这方面的任何文档吗?

We know that Mocking DBContext in Unit testing is bad practice, however how about creating an Interface over it?我们知道单元测试中的 Mocking DBContext 是不好的做法,但是如何在它上面创建一个接口呢?

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

"However, we never try to mock DbContext or IQueryable. Doing so is difficult, cumbersome, and fragile. Don't do it." “但是,我们从不尝试模拟 DbContext 或 IQueryable。这样做很困难、麻烦且脆弱。不要这样做。”

Resources: Why DbContext doesn't implement IDbContext interface?资源: 为什么 DbContext 不实现 IDbContext 接口?

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.如果您的目标是促进与 DbContext 交互的单元测试代码,那么我建议您考虑在工作单元旁边实现存储库模式来管理 DbContext 生命周期 scope 和提交。 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? )我已经在各种答案中概述了实现灵活且易于测试的存储库类的有效方法,但这个可能总结得最好:( 如何在存储库模式上从 Entity Framework Core 设置多个服务?

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.我建议避免使用通用存储库实现并采用 EF 的IQueryable支持的强大功能来构建一个极其简单的模拟层,以提供高效和灵活的查询。

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 )最后一个细节是,如果您确实希望通过存储库支持async查询并希望对它们进行单元测试,可以在此处找到支持此功能的宝贵提示:( 使用内存中的 Unit-testing.ToListAsync()

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

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