ef 并發控制

ef 并發控制

ef 并發控制

什么是并發?
并發分悲觀并發和樂觀并發。
悲觀并發:比如有兩個用戶A,B,同時登錄系統修改一個文檔,如果A先進入修改,則系統會把該文檔鎖住,B就沒辦法打開了,只有等A修改完,完全退出的時候B才能進入修改。
樂觀并發:同上面的例子,A,B兩個用戶同時登錄,如果A先進入修改緊跟著B也進入了。A修改文檔的同時B也在修改。如果在A保存之后B再保存他的修改,此時系統檢測到數據庫中文檔記錄與B剛進入時不一致,B保存時會拋出異常,修改失敗。
EF中如何控制并發?
Entity Framework不支持悲觀并發,只支持樂觀并發。
如果要對某一個表做并發處理,就在該表中加一條Timestamp類型的字段。注意,一張表中只能有一個Timestamp的字段。
Data Annotations中用Timestamp來標識設置并發控制字段,標識為Timestamp的字段必需為byte[]類型。
publicclass Person { public int PersonId { get; set; } public int SocialSecurityNumber { get; set; } public string FirstName { get; set; } public string LastName { get; set; } [Timestamp] public byte[] RowVersion { get; set; } }
Fluent API用IsRowVersion方法
modelBuilder.Entity<Person>().Property(p => p.RowVersion).IsRowVersion();
我們看到生成的數據庫中,RowVersion是timestamp類型。
下面我們寫一段代碼來測試一下:
staticvoid Main(string[] args) { var person = new Person { FirstName = "Rowan", LastName = "Miller", SocialSecurityNumber = 12345678 }; //新增一條記錄,保存到數據庫中using (var con = new BreakAwayContext()) { con.People.Add(person); con.SaveChanges(); } var firContext = new BreakAwayContext(); //取第一條記錄,并修改一個字段:這里是修改了FirstName //先不保存var p1 = firContext.People.FirstOrDefault(); p1.FirstName = "Steven"; //再創建一個Context,同樣取第一條記錄,修改LastName字段并保存using (var secContext = new BreakAwayContext()) { var p2 = secContext.People.FirstOrDefault(); p2.LastName = "Francis"; secContext.SaveChanges(); } try { firContext.SaveChanges(); Console.WriteLine(" 保存成功"); } catch (DbUpdateConcurrencyException ex) { Console.WriteLine(ex.Entries.First().Entity.GetType().Name + " 保存失敗"); } Console.Read(); }
上面我們實例化了三個DbContext,第一個增加一條記錄到數據庫中,第二個修改剛增加的記錄但不保存,然后第三個Context也取剛新增的記錄并保存,最后再保存第二個Context,結果保存失敗。
可以看到我們的并發控制取到了作用。
分析EF生成的SQL語句:
exec sp_executesql N'update [dbo].[People] set [LastName] = @0 where (([PersonId] = @1) and ([RowVersion] = @2)) select [RowVersion] from [dbo].[People] where @@ROWCOUNT > 0 and [PersonId] = @1',N'@0 nvarchar(max) ,@1 int,@2 binary(8)',@0=N'Francis',@1=1,@2=0x00000000000007D1
可以看到,它在取對應記錄的時候把RowVersion也作為篩選條件。上面例子中的secContext保存的時候,數據庫中的RowVersion字段的值就變了,所以firContext保存的時候用原來的RowVersion取值,自然就取不到相應的記錄而報錯。
如果我們只是要對某個字段作并發控制呢?別著急,EF也有辦法。
Data Annotations中用ConcurrencyCheck來標識
public class Person { publicint PersonId { get; set; } [ConcurrencyCheck]
public int SocialSecurityNumber { get; set; } public string FirstName { get; set; } public string LastName { get; set; } public byte[] RowVersion { get; set; } }
Fluent API用IsConcurrencyToken方法
modelBuilder.Entity<Person>().Property(p => p.SocialSecurityNumber).IsConcurrencyToken();
上面的實體中,我們將SocialSecurityNumber(社會保險號)標識為開放式并發,也寫一個類似的代碼測試一下:
staticvoid Main(string[] args) { var person = new Person { FirstName = "Rowan", LastName = "Miller", SocialSecurityNumber = 12345678 }; //新增一條記錄,保存到數據庫中using (var con = new BreakAwayContext()) { con.People.Add(person); con.SaveChanges(); } var firContext = new BreakAwayContext(); //取第一條記錄,并修改SocialSecurityNumber字段 //先不保存var p1 = firContext.People.FirstOrDefault(); p1.SocialSecurityNumber = 123; //再創建一個Context,同樣取第一條記錄, //修改SocialSecurityNumber字段并保存using (var secContext = new BreakAwayContext()) { var p2 = secContext.People.FirstOrDefault(); p2.SocialSecurityNumber = 456; secContext.SaveChanges(); } try { firContext.SaveChanges(); Console.WriteLine(" 保存成功"); } catch (DbUpdateConcurrencyException ex) { Console.WriteLine(ex.Entries.First().Entity.GetType().Name + " 保存失敗"); } Console.Read(); }
運行結果同樣是保存失敗,說明我們的并發控制起作用了。
分析一下EF執行的SQL:
exec sp_executesql N'update [dbo].[People] set [SocialSecurityNumber] = @0 where (([PersonId] = @1) and ([SocialSecurityNumber] = @2)) ',N'@0 int,@1 int,@2 int',@0=123,@1=1,@2=12345678
可以看到,EF將我們要并發控制的列SocialSecurityNumber也作為一個篩選條件,這樣firContext保存的時候也會因為的數據庫中SocialSecurityNumber值變了,取不到對應的記錄而更新失敗。
補充一下:如果是EDMX如何將字段設置為Concurrency。很簡單,在對應的字段上右鍵-屬性。在打開的屬性窗口中有一個并發模式,你將它選擇為Fixed即可。
posted on 2018-08-10 22:45 micwin 閱讀(...) 評論(...) ?編輯 收藏

轉載于:https://www.cnblogs.com/chinanetwind/articles/9457873.html

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/279651.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/279651.shtml
英文地址,請注明出處:http://en.pswp.cn/news/279651.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

C#實現寫入文本文件內容功能

private void write_txt(string str1, string str2, string str3)02{03System.DateTime currentTime System.DateTime.Now;04string strYMD currentTime.ToString("d");05string FILE_NAME "MyFileSend" strYMD ".txt";//每天按照日期建立一…

如何在Windows上設置BitLocker加密

BitLocker is a tool built into Windows that lets you encrypt an entire hard drive for enhanced security. Here’s how to set it up. BitLocker是Windows內置的工具&#xff0c;可用于加密整個硬盤驅動器以增強安全性。 設置方法如下。 When TrueCrypt controversially …

Java字節碼方法表與屬性表深度剖析

方法表&#xff1a; 在上一次咱們已經分析到了字段信息了&#xff0c;如下&#xff1a; 緊接著就是方法相關的信息了&#xff1a; 而它展開之后的結構為&#xff1a; 所以往后數2個字節&#xff0c;看一下方法的總數&#xff1a; 3個方法&#xff0c;可咱們只定義了兩個方法呀&…

最大連續子數組和與JUnit測試

【題目】最大連續子數組和&#xff08;最大子段和&#xff09; 背景 問題&#xff1a; 給定n個整數&#xff08;可能為負數&#xff09;組成的序列a[1],a[2],a[3],…,a[n],求該序列如a[i]a[i1]…a[j]的子段和的最大值。當所給的整數均為負數時定義子段和為0&#xff0c;依此定義…

筆記本電源適配器為什么總壞_為什么某些交流適配器和電源會發出嘯叫聲?

筆記本電源適配器為什么總壞Most of the time our AC adapters and power supplies tend to be quiet, but what does it mean when one makes a whining noise? Should you be concerned? Today’s SuperUser Q&A post has the answers to a worried reader’s question…

4412 字符類設備的設備號

一、靜態申請字符類設備號 字符類設備函數在文件"include/linux/fs.h"中內核提供了三個函數來注冊一組字符設備編號&#xff0c;這三個函數分別是 register_chrdev_region()alloc_chrdev_region()register_chrdev()register_chrdev_region()是提前知道設備的主次設備…

monogdb操作system.*權限

mongodb roles system.roles集合刪不掉 當你自定義了特權(角色): db.createRole({role: "dropSystemViewsAnyDatabase",privileges: [{actions: [ "dropCollection" ],resource: { db: "", collection: "system.roles" }}],roles: []}…

如何發現假庫存照片(并將合適的人歸于屬性)

Spammers and other unscrupulous advertisers are always looking for new ways to get you click on their pages. One of the latest tactics is to steal popular and useful stock images—like the kind you sometimes see in news articles—and re-upload them elsewhe…

Mysql Hunter

一、簡介自動化實施的過程中&#xff0c;我們通常都面臨一個棘手的問題&#xff1a;數據的準備和恢復。即在成功執行一個自動化用例時&#xff0c;我們可能需要一定的數據前提&#xff0c;而為了使得整個前提不至于被其他的用例破壞&#xff0c;以至于我們有時不得不在自動化用…

C6748_UART(5) - UART寄存器

1、FIFO控制寄存器&#xff08;FCR&#xff09;RXFIFTL&#xff1a;接收FIFO中斷觸發(當FIFO中的數據量剛到達所要求&#xff08;trigger level&#xff09;的時候會產生中斷);DMAMODE1:如果FIFO使能的話此位可以使能DMA模式。TXCLR&#xff1a;發送FIFO清除。RXCLR&#xff1a…

如何在Windows 10上限制Wi??ndows Update的下載帶寬

Windows 10’s Fall Creators Update gives you more control of Windows Update’s downloads and uploads. You can now set a download bandwidth limit, ensuring Windows Update won’t hog your Internet connection with its background downloads. Windows 10的Fall Cr…

Elasticsearch嵌套查詢

2019獨角獸企業重金招聘Python工程師標準>>> 一、背景 最近在做基于宴會廳檔期的商戶搜索推薦時&#xff0c;如果用傳統平鋪式的mapping結構&#xff0c;無法滿足需求場景&#xff0c;于是用到了Elasticsearch支持的Nested(嵌套)查詢。 二、普通對象與嵌套對象的索引…

寫給深圳首期Python自動化開發周未班的信

你是否做了正確的決定&#xff1f; 深圳首期周未班的同學們大家好&#xff0c;我是Alex, 老男孩教育的聯合創始人&#xff0c;Python項目的發起人&#xff0c;51CTO學院連續2屆最受學員喜愛的講師&#xff0c;中國最早一批使用Python的程序員&#xff0c;當然還有一堆頭銜&…

網站跳出率的相關要點介紹

今天小峰seo博客和大家一起來探討關于“網站跳出率的相關要點”&#xff0c;這里大體是分為三大要點&#xff1a;首先是進入的流量渠道&#xff0c;然后就是綜合流量速度和內容的質量問題&#xff0c;細的來說就是我們的網站進來的用戶是搜索什么關鍵詞來的是通過百度還是搜狗或…

如何使用PowerShell提升開發效率(以Windows Embedded CE為例)

簡介 本文講述如何使用Powershell通過RAPI來控制Windows Embedded CE和Windows Mobile設備。 緣由 我入行的時候是做AS400 RPG和UNIX C開發的&#xff0c;所有開發環境都是字符界面&#xff0c;因此習慣了vigrepmake的開發模式。后來開始做Windows的開發&#xff0c;開始也不大…

視頻圖像傳輸學習筆記-基礎小知識(一)

攝像頭DVP與MIPI區別 DVP是并口&#xff0c;需要PCLK、VSYNC、HSYNC、D[0&#xff1a;11]——可以是8/10/12bit數據&#xff0c;看ISP或baseband是否支持&#xff1b;總線PCLK極限大約在96M左右&#xff0c;而且走線長度不能過長&#xff0c;所有DVP最大速率最好控制在72M以…

java程序員面試交流項目經驗

粘貼自&#xff1a;https://blog.csdn.net/wangyuxuan_java/article/details/8778211 1&#xff1a;請你介紹一下你自己 這是面試官常問的問題。一般人回答這個問題過于平常&#xff0c;只說姓名、愛好、工作經驗&#xff0c;這些簡歷上都有。其實&#xff0c;面試官最希望知道…

Windows7旗艦版磁盤分區詳解—附分區步驟截圖

最近工作中配置使用聯想的Thinkpad TL系列本本.當然原裝的系統時剛發布的Windows RTM旗艦版.在考慮買之前也參考了戴爾 蘋果的等等, 但個人私下也是一直在用Tinkpad系列, 相比其他的品牌本人還是比較鐘情于Tinkpad 非常實用的鍵盤. 以及簡潔的外觀.買回來一看這個TL系列原裝的系…

outlook存檔郵件_如何在Outlook 2013中存檔電子郵件

outlook存檔郵件We’ve always been told that backing up our data is a good idea. Well, that same concept can extend to email as well. You may want to archive your email every so often, such as monthly, quarterly, or even yearly. 我們一直被告知備份數據是一個…

洛谷 P1736 創意吃魚法(多維DP)

題目描述 回到家中的貓貓把三桶魚全部轉移到了她那長方形大池子中&#xff0c;然后開始思考&#xff1a;到底要以何種方法吃魚呢&#xff08;貓貓就是這么可愛&#xff0c;吃魚也要想好吃法 ^_*&#xff09;。她發現&#xff0c;把大池子視為01矩陣&#xff08;0表示對應位置無…