Make the DbContext Ambient with UnitOfWorkScope(now named DbContextScope by mehdime)
The Entity Framework DbContext (or LINQ-to-SQL DataContext) is a Unit Of Work implementation. That means that the same DbContext should be used for all operations (both reading and writing) within a single web or service request. That means that there are a lot of different places where the DbContext have to be accessed. To avoid having to pass the DbContext around as a parameter, I’ve created a UnitOfWorkScope that makes the DbContext ambient and easily accessible.
A common beginners problem when working with Entity Framework or LINQ-to-SQL is to have too short life times of the DbContext. A problem that I’ve seen many questions about on Stack Overflow is when questions are encapsulated in repositories or helper methods. Inside each method a new DbContext is created for that specific read. Later, when the returned entity has been updated and is to be saved the problem occurs. The entity should be saved using the same DbContext that once read it from the database to allow change tracking to work properly. Clearly, having separate DbContexts is a problem.
The first attempt to solve it is usually to pass the DbContext around. That only solves half the problem though, that of accessing it. The other half of the problem is to decide where to call SaveChanges to persist the changes done. Calling it from every method making changes spoils the entire unit of work concept. Trusting the creator of the context to know when any of a myriad of called functions have made changes seems risky.
I’ve been looking for a better way to handle the DbContext and have come up with an ambient DbContext, using a UnitOfWorkScope which is similar to TransactionScope.
The main features of the UnitOfWorkScope are:
- The first method in the call chain opening a
UnitOfWorkScopecreates an ambient DbContext. - Subsequent methods in the call chain utilizes the same DbContext.
- Changes are only saved if all participating scopes called
SaveChanges - Read only mode is available, where data is read using the existing DbContext, but no changes need to be saved. This is useful for GetSomeThing methods that are used both for pure reading and for reading for update.
A Shared Query
A shared query uses the UnitOfWorkScope, instead of creating a DbContext instance directly.
public static Entities.Car GetCar(int id) |
The reading purpose is used to mark that this unit of work scope will not do any updates, so SaveChanges will not be called. The method can be used both standalone to read data, or to fetch data for subsequent update. Let’s look at using it for updating.
using (var uow = new UnitOfWorkScope<CarsContext>(UnitOfWorkScopePurpose.Writing)) |
Here, the scope is opened for writing. Leaving the scope without calling SaveChanges indicates an error, just like Complete works on TransactionScope.
Experiences of Using the UnitOfWorkScope
We’re using the unit of work scope in my current project. The experience so far is that we’ve removed the need to pass around DbContext instances all over. It is also much easier to reuse the same common set of base queries for reading and for writing. Any method can easily get hold of the ambient scope. A business logic method on an entity can a service method, which can now be part of the same unit of work without having to pass the DbContext around.
The UnitOfWorkScope code
The code makes use of the Disposable base class, that I’ve written about before. The code is also available on GitHub.
/// <summary> |
The code has been updated with a better way to handle when a writing scope is opened to a reading root scope. In this version, an exception is thrown when the child scope is opened. Previously the exception was thrown when the root scope was disposed.
The code is written to be easy to use right and hard to use wrong. There is a risk that someone would call SaveChanges directly on the wrapped DbContext – possibly saving changes early. To avoid that there is a guard which disallows that.
The code is thread safe as it uses thread local storage to store the current scope. However it will probably not work with async/await as it does not consider the synchronization context but rather is tied to the thread directly.
from:https://coding.abel.nu/2012/10/make-the-dbcontext-ambient-with-unitofworkscope/
Make the DbContext Ambient with UnitOfWorkScope(now named DbContextScope by mehdime)的更多相关文章
- Managing DbContext the right way with Entity Framework 6: an in-depth guide by mehdime
UPDATE: the source code for DbContextScope is now available on GitHub: DbContextScope on GitHub. A b ...
- DbContextScope,A simple and flexible way to manage your Entity Framework DbContext instances,by mehdime
DbContextScope A simple and flexible way to manage your Entity Framework DbContext instances. DbCont ...
- EF6 Database First (DbContext) - Change Schema at runtime
Problem:There are two SQL databases (dev and live) with on Azure which has identical table structure ...
- 在EntityFramework6中管理DbContext的正确方式——3环境上下文DbContext vs 显式DbContext vs 注入DbContext(外文翻译)
(译者注:使用EF开发应用程序的一个难点就在于对其DbContext的生命周期管理,你的管理策略是否能很好的支持上层服务 使用独立事务,使用嵌套事务,并行执行,异步执行等需求? Mehdi El Gu ...
- 在EntityFramework6中管理DbContext的正确方式——4DbContextScope:一个简单的,正确的并且灵活的管理DbContext实例的方式(外文翻译)
(译者注:使用EF开发应用程序的一个难点就在于对其DbContext的生命周期管理,你的管理策略是否能很好的支持上层服务 使用独立事务,使用嵌套事务,并行执行,异步执行等需求? Mehdi El Gu ...
- EF Core 2.0中Transaction事务会对DbContext底层创建和关闭数据库连接的行为有所影响
数据库 我们先在SQL Server数据库中建立一个Book表: CREATE TABLE [dbo].[Book]( ,) NOT NULL, ) NULL, ) NULL, ) NULL, [Cr ...
- MVC模式下unity配置,报错“No connection string named '**Context' could be found in the application config file”
写在前面: 第一次配置时好好的,后来第二次改到MVC模式,把依赖注入写成字典的单例模式时,由于新建的ORM(数据库映射模型EF),怎么弄都不用,一直报错"No connection str ...
- EntityFramework Core 1.1是如何创建DbContext实例的呢?
前言 上一篇我们简单讲述了在EF Core1.1中如何进行迁移,本文我们来讲讲EF Core1.1中那些不为人知的事,细抠细节,从我做起. 显式创建DbContext实例 通过带OnConfiguri ...
- Entity Framework 教程——DBContext
DBContext: 在之前的章节<创建实体数据模型>中,EDM为我们创建了SchoolDBEntities 类,它派生子System.Data.Entity.DbContext这个类,这 ...
随机推荐
- input文本框禁止修改文本——disabled和readonly属性的作用及区别
1.input文本框禁止修改文本 disabled属性:<input type="text" name="name" value="xxx&qu ...
- 【ARTS】01_08_左耳听风-20181231~20190106
ARTS: Algrothm: leetcode算法题目 Review: 阅读并且点评一篇英文技术文章 Tip/Techni: 学习一个技术技巧 Share: 分享一篇有观点和思考的技术文章 Algo ...
- 【转载】maven pom详解(2)
setting.xml主要用于配置maven的运行环境等一系列通用的属性,是全局级别的配置文件:而pom.xml主要描述了项目的maven坐标,依赖关系,开发者需要遵循的规则,缺陷管理系统,组织和li ...
- ispoweroftwo 判断2的次幂【转】
转自:https://www.cnblogs.com/troublelost/p/5236391.html 首先结果是: public bool IsPowerOfTwo(int n) { if(n& ...
- Python 优雅获取本机 IP 方法
原文 见过很多获取服务器本地IP的代码,个人觉得都不是很好,例如以下这些 不推荐:靠猜测去获取本地IP方法 #!/usr/bin/env python # -*- coding: utf-8 -*- ...
- 【linux kernel】 中断处理-中断上半部【转】
转自:http://www.cnblogs.com/embedded-tzp/p/4451354.html 欢迎转载,转载时需保留作者信息,谢谢. 邮箱:tangzhongp@163.com 博客园地 ...
- 解决centos7下tomcat启动正常,无法访问项目的问题
centos7防火墙不再采用iptables命令,改用firewalld 禁用防火墙命令: # systemctl stop firewalld.service # systemctl disable ...
- 如何使用windows的计划任务?计划任务?
我们经常有一些程序想要过了几小时来运行:比如定时关机 或者说希望能够每天的几点执行一个什么程序: 这些所有的操作都需要用到windows的任务计划:或者叫计划任务:反正都一样 下面小编将指导大家创建一 ...
- KnockoutJs学习笔记(八)
with binding用于创建一个新的绑定环境(binding context),包含with binding的元素的所有子元素都将处于指定的object的环境限定内. 下面是一个简单的使用with ...
- 2.选择元素 - 自定义过滤器《jquery实战》
2.5.6 自定义过滤器 jQuery 中有两种方法创建自定义的过滤器.第一种比较简单,但是不鼓励,从 jQuery 1.8 开始已经被第二种方法取代.记住,使用新方法时,你自定义的过滤器在 jQue ...