且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

C#中的实体框架:你的资料库类中正确使用的DbContext类

更新时间:2023-02-17 20:08:05

不应该遵循的第一篇文章,我会告诉你为什么。

You should not follow the first article, and I will tell you why.

随着你的所有功能失去相当多的第一种​​方法该实体框架通过的DbContext提供,包括它的1级高速缓存,其身份地图,其单位的工作,其变化的跟踪和懒加载能力。这是因为在上面的场景中,为每个数据库查询创建和设置随即一个新的的DbContext 实例,从而防止的DbContext 例如从能够跟踪整个业务的交易数据对象的状态。

Following the first approach you're loosing pretty much every feature that Entity Framework provides via the DbContext, including its 1st-level cache, its identity map, its unit-of-work, and its change tracking and lazy-loading abilities. That's because in the scenario above, a new DbContext instance is created for every database query and disposed immediately afterwards, hence preventing the DbContext instance from being able to track the state of your data objects across the entire business transaction.

有一个的DbContext 如在你的仓库类中的私有财产也有它的问题。我认为更好的办法是有一个CustomDbContextScope。这种做法是很好的被这家伙解释说:迈赫迪萨尔瓦多Gueddari

Having a DbContext as a private property in your repository class also has its problems. I believe the better approach is having a CustomDbContextScope. This approach is very well explained by this guy: Mehdi El Gueddari

这文章的http://mehdi.me/ambient-dbcontext-in-ef6/ 是我见过有关的EntityFramework的***的文章。你应该完全读它,我相信它会回答你所有的问题。

This article http://mehdi.me/ambient-dbcontext-in-ef6/ is the best article about EntityFramework I've ever seen. You should read it entirely, and I believe it will answer all your questions.