tnblog
首页
视频
资源
登录

EF CORE 6使用事务。entity framework

3858人阅读 2023/2/24 9:41 总访问:824538 评论:0 收藏:0 手机
分类: ORM

如果出现错误:The connection is already in a transaction and cannot participate in another transaction.可以进行一下判断

  1. var transaction = Database.CurrentTransaction ?? Database.BeginTransaction()

Try to use this helper function for creating a new transaction:

  1. public CommittableTransaction CreateTransaction()
  2. => new System.Transactions.CommittableTransaction(new TransactionOptions()
  3. {
  4. IsolationLevel = System.Transactions.IsolationLevel.ReadCommitted
  5. });

Using the Northwind database as example database, you can use it like:

  1. public async Task<int?> CreateCategoryAsync(Categories category)
  2. {
  3. if (category?.CategoryName == null) return null;
  4. using(var trans = CreateTransaction())
  5. {
  6. await this.Context.Categories.AddAsync(category);
  7. await this.Context.SaveChangesAsync();
  8. trans.Commit();
  9. return category?.CategoryID;
  10. }
  11. }

And then you can call it from another function like:

  1. /// <summary>Create or use existing category with associated products</summary>
  2. /// <returns>Returns null if transaction was rolled back, else CategoryID</returns>
  3. public async Task<int?> CreateProjectWithStepsAsync(Categories category)
  4. {
  5. using var trans = CreateTransaction();
  6. int? catId = GetCategoryId(category.CategoryName)
  7. ?? await CreateCategoryAsync(category);
  8. if (!catId.HasValue || string.IsNullOrWhiteSpace(category.CategoryName))
  9. {
  10. trans.Rollback(); return null;
  11. }
  12. var product1 = new Products()
  13. {
  14. ProductName = "Product A1", CategoryID = catId
  15. };
  16. await this.Context.Products.AddAsync(product1);
  17. var product2 = new Products()
  18. {
  19. ProductName = "Product A2", CategoryID = catId
  20. };
  21. await this.Context.Products.AddAsync(product2);
  22. await this.Context.SaveChangesAsync();
  23. trans.Commit();
  24. return catId;
  25. }

To run this with LinqPad you need an entry point (and of course, add the NUGET package EntityFramework 6.x via F4, then create an EntityFramework Core connection):

  1. // Main method required for LinqPad
  2. UserQuery Context;
  3. async Task Main()
  4. {
  5. Context = this;
  6. var category = new Categories()
  7. {
  8. CategoryName = "Category A1"
  9. // CategoryName = ""
  10. };
  11. var catId = await CreateProjectWithStepsAsync(category);
  12. Console.WriteLine((catId == null)
  13. ? "Transaction was aborted."
  14. : "Transaction successful.");
  15. }

This is just a simple example - it does not check if there are any product(s) with the same name existing, it will just create a new one. You can implement that easily, I have shown it in the function CreateProjectWithStepsAsync for the categories:

  1. int? catId = GetCategoryId(category.CategoryName)
  2. ?? await CreateCategoryAsync(category);

First it queries the categories by name (via GetCategoryId(…)), and if the result is null it will create a new category (via CreateCategoryAsync(…)).

Also, you need to consider the isolation level: Check out System.Transactions.IsolationLevel to see if the one used here (ReadCommitted) is the right one for you (it is the default setting).

What it does is creating a transaction explicitly, and notice that here we have a transaction within a transaction.

原文:https://stackoverflow.com/questions/70958670/how-to-nest-transactions-in-ef-core-6


欢迎加群讨论技术,1群:677373950(满了,可以加,但通过不了),2群:656732739。有需要软件开发,或者学习软件技术的朋友可以和我联系~(Q:815170684)

评价

EF删除与批量删除。entity framework删除与批量删除

[TOC]EF删除方法1:直接执行数据库int count = oapEntities.Database.ExecuteSqlCommand(&quot;delete from users where id...

EF添加。entity framework添加。abp vnext ef 添加,批量添加的封装

EF的添加如下,代码比较添加: ShipEntities se = new ShipEntities(); se.Users.Add(user); se.SaveChanges(); 方法2:...

NET core 使用 EF Code First

下面这些内容很老了看这篇:https://www.tnblog.net/aojiancc2/article/details/5365 项目使用多层,把数据库访问...

.net mvc分部页,.net core分部页

.net分部页的三种方式第一种:@Html.Partial(&quot;_分部页&quot;)第二种:@{ Html.RenderPartial(&quot;分部页&quot;);}...

StackExchange.Redis操作redis(net core支持)

官方git开源地址https://github.com/StackExchange/StackExchange.Redis官方文档在docs里边都是官方的文档通过nuget命令下...

.net core 使用session

tip:net core 2.2后可以直接启用session了,不用在自己添加一次session依赖,本身就添加了使用nuget添加引用Microsoft.AspN...

通俗易懂,什么是.NET?什么是.NET Framework?什么是.NET core?

朋友圈@蓝羽 看到一篇文章写的太详细太通俗了,搬过来细细看完,保证你对.NET有个新的认识理解原文地址:https://www.cnblo...

asp.net core2.0 依赖注入 AddTransient与AddScoped的区别

asp.net core主要提供了三种依赖注入的方式其中AddTransient与AddSingleton比较好区别AddTransient瞬时模式:每次都获取一...

.NET core 使用 Kestrel

Kestrel介绍 Kestrel是一个基于libuv的跨平台web服务器 在.net core项目中就可以不一定要发布在iis下面了Kestrel体验可以使...

Net core中使用cookie

net core中可以使用传统的cookie也可以使用加密的cookieNET CORE中使用传统cookie设置:HttpContext.Response.Cookies.Appe...

NET core项目结构简单分析

一:wwwrootwwwroot用于存放网站的静态资源,例如css,js,图片与相关的前端插件等lib主要是第三方的插件,例如微软默认引用...

Net core使用EF之DB First

一.新建一个.net core的MVC项目新建好项目后,不能像以前一样直接在新建项中添加ef了,需要用命令在添加ef的依赖二.使用Nug...

.net core使用requestresponse下载文件下载excel等

使用request获取内容net core中request没有直接的索引方法,需要点里边的Query,或者formstringbase64=Request.Form[&quot;f...

iframe自适应高度与配合net core使用

去掉iframe边框frameborder=&quot;0&quot;去掉滚动条scrolling=&quot;no&quot;iframe 自适应高度如果内容是固定的,那么就...

net core启动报错Unable to configure HTTPS endpoint. No server certificate was specified

这是因为net core2.1默认使用的https,如果使用Kestrel web服务器的话没有安装证书就会报这个错其实仔细看他的错误提示,其...
这一生多幸运赶上过你.
排名
3
文章
317
粉丝
22
评论
14
ICP备案 :渝ICP备18016597号-1
网站信息:2018-2025TNBLOG.NET
技术交流:群号656732739
联系我们:contact@tnblog.net
公网安备:50010702506256
欢迎加群交流技术