一、EF事務
引用程序集
using System.Transactions;
用法
var writer = new System.IO.StringWriter(); try { using (var ts = new TransactionScope()) { using (var db = new EfContext()) { //TODO } ts.Complete(); } } catch (TransactionAbortedException ex) { writer.WriteLine("TransactionAbortedException Message: {0}", ex.Message); } catch (ApplicationException ex) { writer.WriteLine("ApplicationException Message: {0}", ex.Message); }
參考文章:https://www.cnblogs.com/CreateMyself/p/4787856.html
DBContext與SqlClient
可用於ef和ado.net(SqlBulkCopy)的事務統一處理,_context為DbContext
var dbConnection = (SqlConnection)_context.Database.Connection; var trans = (SqlTransaction)_context.Database.CurrentTransaction.UnderlyingTransaction;
二、常見問題
1.在多語句事務內不允許使用 CREATE DATABASE 語句
一、問題
使用ef codefirst開發,無法創建數據庫的問題,如下提示
Server Error in '/' Application. 在多語句事務內不允許使用 CREATE DATABASE 語句。 Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. Exception Details: System.Data.SqlClient.SqlException: 在多語句事務內不允許使用 CREATE DATABASE 語句。 Source Error: Line 32: */ Line 33: public ZmBlogDbContext(string nameOrConnectionString) Line 34: : base(nameOrConnectionString) Line 35: { Line 36:
二、解決方法
這是 EF 拋出的異常,只要先創建好數據庫就可以了
create database [ZmBlog]
提示:
這個錯誤是在第一次運行abp出現的,創建數據庫后,這時要使用 update-database 進行數據遷移,否則基礎數據是空的