Entity Framework中的批量提交与事务处理

EntityFramework.BulkInsert:EntityFramework6的快速批量插入 EntityFramework.BulkInsert 从Codeplex站点上的原始版本更新了EntityFramework.BulkInsert的端口。 这不是我的原始项目,而是继续进行并添加较小的更新和支持。 原始文件托管在Codeplex上,但后来被删除了。 从那时起,该项目就获得了对异步IO的支持,错误修复,显式事务支持以及对MySql的支持。 NuGet 有几种可用的NuGet软件包: EntityFramework6.BulkInsert EntityFramework6.BulkInsert.SqlServerCe EntityFramework6.BulkInsert.MySql 目的 该库的目的是使用EntityFramework 6和您现有的DbContext实例执行批量插入,以执行更快的插入,而不是为一组强类型对象生成多个insert语句。 用法 IEnumerable < Car> cars = GenerateCars (); using ( var context = GetDbContext ()) { context . Bulk 立即下载

TransactionScope是.Net Framework 2.0滞后,新增了一个名称空间。它的用途是为数据库访问提供了一个“轻量级”[区别于:SqlTransaction]的事物。使用之前必须添加对 System.Transactions.dll 的引用。


在Entity Framework 中使用SaveChanges()是很频繁的,单次修改或删除数据后调用SaveChanges()返回影响记录数。

要使用批量修改或者批量删除数据,就需要SaveChanges(false)+AcceptAllChanges()方法了。


 SaveChanges(false) 只是通知EF需要对数据库执行的操作,在内存中是属于挂起状态,在必要的时候是可以撤销的,比如AcceptAllChange()提交为真正成功,EF将撤销SaveChanges(false)的操作。


 而在处理分布式事务操作的时候,就有必要使用TransactionScope 来处理了,很多时候我们会这样写:

using (TransactionScope scope = new TransactionScope())
{
    //Do something with context1
    //Do something with context2

    //Save and discard changes
    context1.SaveChanges();

    //Save and discard changes
    context2.SaveChanges();

    //if we get here things are looking good.
    scope.Complete();
}
但是这样写是有风险的,假 

如context1.SaveChanges()成功了,context2.SaveChanges()却是有问题的,我们在scope.Complete()提交事务的时候就会终止,而Context1已经成功执行了

这可能不一定符合我们的需要。如果我们需要 context1、context2要不同时执行成功,要不都不成功,我们需要对代码作小小的调整,如用下面的代码: 

 

using (TransactionScope scope = new TransactionScope())
{
    //Do something with context1
    //Do something with context2

    //Save Changes but don't discard yet
    context1.SaveChanges(false);

    //Save Changes but don't discard yet
    context2.SaveChanges(false);

    //if we get here things are looking good.
    scope.Complete();
    context1.AcceptAllChanges();
    context2.AcceptAllChanges();

}
我们用SaveChanges(false)先将必要的数据库操作命令发送给数据库,这是注意context1与context2并没有真正发生改变,如果事务终止,自动回滚,两者的更改都没有真正提交到数据库,所以是可以成功回滚的。

在Entity Framework 中使用SaveChanges()是很频繁的,单次修改或删除数据后调用SaveChanges()返回影响记录数。

要使用批量修改或者批量删除数据,就需要SaveChanges(false)+AcceptAllChanges()方法了。


 SaveChanges(false) 只是通知EF需要对数据库执行的操作,在内存中是属于挂起状态,在必要的时候是可以撤销的,比如AcceptAllChange()提交为真正成功,EF将撤销SaveChanges(false)的操作。


 而在处理分布式事务操作的时候,就有必要使用TransactionScope 来处理了,很多时候我们会这样写:

using (TransactionScope scope = new TransactionScope())
{
    //Do something with context1
    //Do something with context2

    //Save and discard changes
    context1.SaveChanges();

    //Save and discard changes
    context2.SaveChanges();

    //if we get here things are looking good.
    scope.Complete();
}
但是这样写是有风险的,假 

如context1.SaveChanges()成功了,context2.SaveChanges()却是有问题的,我们在scope.Complete()提交事务的时候就会终止,而Context1已经成功执行了

这可能不一定符合我们的需要。如果我们需要 context1、context2要不同时执行成功,要不都不成功,我们需要对代码作小小的调整,如用下面的代码: 

 

using (TransactionScope scope = new TransactionScope())
{
    //Do something with context1
    //Do something with context2

    //Save Changes but don't discard yet
    context1.SaveChanges(false);

    //Save Changes but don't discard yet
    context2.SaveChanges(false);

    //if we get here things are looking good.
    scope.Complete();
    context1.AcceptAllChanges();
    context2.AcceptAllChanges();

}
我们用SaveChanges(false)先将必要的数据库操作命令发送给数据库,这是注意context1与context2并没有真正发生改变,如果事务终止,自动回滚,两者的更改都没有真正提交到数据库,所以是可以成功回滚的。

转载自:http://www.cnblogs.com/hyl8218/archive/2011/10/10/2205576.html 感谢原作者
Three.js 完整实战项目:构建一个 3D 商品展示空间 Three.js 作为强大的 WebGL 框架,广泛应用于交互式 3D 场景开发,尤其适合创建沉浸式商品展示空间。本文将通过一个完整的实战项目,展示如何构建一个 3D 商品展示空间,涵盖项目架构、资源组织、多模型切换、交互热点绑定、移动端适配和帧率优化。项目以展示虚拟商品(如家具或电子产品)为核心,结合用户交互,基于 Vite、TypeScript 和 Tailwind CSS,支持 ES Modules,确保响应式布局,遵循 WCAG 2.1 可访问性标准。本文适合希望通过综合项目掌握 Three.js 阅读详情

相关推荐

西门子 S7-200 SMART 系列六:手把手教你配置S7-200 SMART Modbus RTU

Modbus 是公开通信协议,其最简单的串行通信部分仅规定了在串行线路的基本数据传输格式。Modbus 具有两种串行传输模式,ASCII 和 RTU,它们定义了数据如何打包、解码的不同方式。支持 Modbus 协议的设备一般都支持 RTU 格式。

John_09040211的博客 7431

[EF]事务管理+批量删除

using (var transaction = context.Database.BeginTransaction()) { try { //删除合同主表信息 FAContract fa = GetFAContract(); context.Entry(fa).State...

德仔 1192

拒绝无意义刷屏,打造高效率热点追踪,极空间部署『TrendRadar』

今天的这个项目确实不错,通过部署在极空间NAS之后,我们就能一直不间断的获取到自己想要看到的新闻或者信息。项目的设置项其实有很多,有兴趣的小伙伴可以在部署之后自己慢慢挖掘~目前年终大促正在火热进行中,极空间NAS不管是新品还是之前在售的畅销型号都有专属的优惠,并且还能叠加国补、平台优惠等福利,享受180天换新以及2年质保服务 ,更有抽奖、晒单等活动,喜欢的小伙伴赶快冲吧!

qq_63499861的博客 2292

Entity Framework Core 7中高效地进行批量数据插入

因为之前的版本中,EF Core无法实现高效地批量插入、修改、删除数据,所以我开发了Zack.EFCore.Batch这个开源项目,比较受大家的欢迎,获得了400多个star。现在支持.NET 7了

nzzackyang的博客 1983

Cisco Packet Tracert 无线路由器配置

Cisco Packet Tracert 无线路由器配置

yushan_caoyu的博客 2万+

RealSense D455启动教程

RealSense D455启动教程 修改rs_camera.launch

每天进步一点点 2417

ef批量添加数据 引入 Z.EntityFramework.Extensions

ef批量添加数据 引入 Z.EntityFramework.Extensions

weixin_46256404的博客 554

i.MX RT1064引脚配置与BGA封装选型实战指南

在嵌入式硬件设计中,引脚配置与PCB布局是连接芯片手册与物理实现的关键桥梁,直接影响系统的稳定性与信号完整性。其核心原理在于理解处理器的IOMUX(输入/输出多路复用器)系统与多电源域架构,前者通过软件配置实现引脚功能的灵活复用,后者则为不同外设接口提供独立的电压基准,是保障电源稳定性的基石。从技术价值看,合理的引脚规划能规避信号干扰、电源不稳等潜在风险,提升设计一次成功率。在应用场景上,无论是连接SDRAM、USB、SDIO等高速外设,还是配置UART、I2C等中低速接口,都需要遵循特定的布局布线规则。本

weixin_33217202的博客 314

Entity Framework和事务

原文:Entity Framework和事务 数据库事务 数据库事务(简称:事务)是数据库管理系统执行过程中的一个逻辑单位,由一个有限的数据库操作序列构成。事务允许以原子方式处理多个数据库操作。 如果已提交事务,则所有操作都会成功应用到数据库。 如果已回滚事务,则所有操作都不会应用到数据库。 数据库事务通常包含了一个序列的对数据库的读/写操作。包含有以下两个目的: 为数据库操作序列提供了一个...

VoldemortChi的博客 568

深入解析UEFI PEI阶段:PeiCore的三次调用与内存管理机制

本文深入解析UEFI启动流程中的PEI阶段,重点探讨PeiCore的三次调用与内存管理机制。详细介绍了PeiCore在临时内存中的初始化、堆栈切换至永久内存的过程,以及最终交接给DXE阶段的关键步骤,为开发者提供调试技巧与实战案例,助力解决UEFI启动问题。

weixin_28452161的博客 650

【嵌入式Linux驱动开发】二十四、Linux I2C 驱动上手尝试

  人的前程关于眼界、关乎格局。   志之所趋,无远弗届,穷山复海不能限也;   志之所向,无坚不入,锐兵精甲不能御也。 一、I2C驱动框架简介   Linux内核将 I2C 驱动分为两部分: ①、 I2C 总线驱动, I2C 总线驱动就是 SOC 的 I2C 控制器驱动,也叫做 I2C 适配器驱动。 ②、 I2C 设备驱动, I2C 设备驱动就是针对具体的 I2C 设备而编写的驱动。 1....

悟已往之不谏 知来者之可追 1068

EF 批量添加

右键资源管理器,找到NuGet程序包,安装Z.EntityFramework.Extensions 将要添加的数据放在list集合当中 db.BulkInsert(list); db.SaveChanges(); 示例: using (DBClassEntities db = new DBClassEntities()) { var list = new List<tb_Degree>(); for (int i = 0; i < 5; i++) { var dgr = new tb_.

qq_51462774的博客 772

FastAPI 极简教程(偏实战,一篇搞定)

本文是一篇FastAPI实战教程,通过最少的概念讲解快速掌握FastAPI的核心功能。文章首先介绍FastAPI是基于Starlette和Pydantic的高性能Python API框架,具有自动生成文档、类型驱动校验、异步支持和依赖注入等优势。教程从安装环境开始,演示了如何创建最小项目并编写第一个"Hello World"接口。接着详细讲解了路由参数处理(Path/Query/Body)、Pydantic数据模型校验、响应模型控制、状态码设置等核心功能。在高级功能方面,重点介绍了错误处

AI天才研究院 815

Entity Framework中的批量提交与事务处理[转]

转自: http://www.cnblogs.com/dudu/archive/2011/04/06/entity_framework_transaction.html在Entity Framework 中使用SaveChanges()是很频繁的,单次修改或删除数据后调用SaveChanges()返回影响记录数。要使用批量修改或者批量删除数据,就需要SaveChanges(...

122

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

精雕软件(JDpaint) 5.5 绿色版

精雕软件(JDpaint) 5.5 绿色版精雕软件(JDpaint) 5.5 绿色版精雕软件(JDpaint) 5.5 绿色版

Entity Framework中 批量提交 事务处理

Entity Framework中的批量提交与事务处理2011-3-24 15:30:25中文系列评论(0)浏览(1886) 在Entity Framework 中使用SaveChanges()是很频繁的,单次修改或删除数据...

cixieku3433的博客 134

SIMATIC S7-1200, S7-1500 PID 控制[手册]

SIMATIC S7-1200, S7-1500 PID 控制[手册]

Entity Framework中的多个库操作批量提交、事务处理

在Entity Framework 中使用SaveChanges()是很频繁的,单次修改或删除数据后调用SaveChanges()返回影响记录数。 要使用批量修改或者批量删除数据,就需要SaveChanges(false)+AcceptAllChanges()方法了。 SaveChanges(false) 只是通知EF需要对数据库执行的操作,在内存中是属于挂起状态,在必要的时候是可以撤...

weixin_30824277的博客 357

计算机控制技术及应用

《计算机控制技术及应用》通过总结作者的科研成果和吸收国内外的先进理论、方法和技术,以计算机控制系统的网络化、开放化、智能化和集成化发展趋势为主线索,主要介绍计算机控制系统的基本概念和计算机控制系统的典型形式,计算机控制系统的数学描述与基本分析方法,以及数字PID控制器、最少拍控制系统、达林算法、状态变量设计法等设计方法及其各种改进算法。重点突出计算机控制系统输入输出通道接口的设计方法和典型控制系统的设计案例与实现方法等。

Entity Framework4.5及之前的批量提交与事务处理

在Entity Framework 中使用SaveChanges()是很频繁的,单次修改或删除数据后调用SaveChanges()返回影响记录数。 要使用批量修改或者批量删除数据,就需要SaveChanges(false)+AcceptAllChanges()方法了。  SaveChanges(false) 只是通知EF需要对数据库执行的操作,在内存中是属于挂起状态,在必要的时候是可以

1081

[EF]事务处理

EF支持事务处理操作,以下语句会获取当前DbContext对象专用的DbContextTransaction()事务处理对象 DbContextTransaction transaction=context.Database.BeginTransaction(); 获取transaction之后,期间任何与context有关的数据操作均会纳入此事务处理的范围中,调用transaction.Com...

德仔 3072

Entity 单数据库服务器的事物处理

2019独角兽企业重金招聘Python工程师标准>>> ...

weixin_34014277的博客 111

Linq 实现EF的删除功能

Linq 实现EF的删除功能 首先说一下Linq操作EF做批量删除(技术暂时达不到) 方法一 用循环的方法实现删除 //查询到数据 EF ctx=new EF(); //数据源 var delete_TB= ctx.tble(表).Where(p =>p.TB001== “xxx”).ToList(); //开启事务,目的为了中途报错数据可以回滚 using (var transact = ctx.Database.BeginTransaction()) { foreach (var item

a751665281的博客 689

【Entity Framework Core事务处理终极指南】:掌握高性能事务编程的5大核心技巧

掌握Entity Framework Core事务处理的高效方法,解决数据一致性难题。涵盖并发控制、显式事务管理、SaveChanges与异步操作的最佳实践,适用于高并发场景。提升性能与可靠性,值得收藏。

FuncFun的博客 773

Entity Framework的事务处理

在ef6之前,ef对事务处理都是隐式处理的,从ef6开始可以手动显示进行处理了。需要明确的一点是:ef所有版本对select的操作除外,其他的增删改操作在执行savechanges()函数后均自动包装成事务处理的。 ...

知易行难的博客 323
上一篇: C#利用Xml Transform把xml和Xlst转换为html
下一篇: TransactionScope使用说明
蝶恋花雨
博客等级 码龄21年 1290粉丝 147原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值