[英]Transaction between different contexts using EF
我有一個項目,我想創建一個與db相關的概念分離,並建議重用。 我使用帶有mysql(devart)連接器的EF,並且我想創建一個事務,該事務在某個表中創建注冊表並將該注冊表鏈接到其他表(如果發生其他情況,則回滾)
我將提供一個虛擬場景,以解釋該過程:
Generic.edmx:
Person {Id, Name, Address, ...}
MyApp.edmx (contains my app database, who uses Generic tables)
Person {Id, Name, Address, ...}
Schedule{ScheduleId, Date, PersonId(FK), ...}
一些要點:
在我的方法createSchedule中,我需要創建一個人並將該人鏈接到時間表。 我已經創建了createPerson(...)方法,該方法返回此ID。 我需要使用此ID鏈接到新的時間表注冊表,因此我需要此事務操作,因此我創建了一個具有兩個上下文的事務范圍,第一個上下文創建人員,第二個上下文創建時間表。 所有上下文以ctx.saveChanges()結尾,但是在第二個上下文中,我面臨與鎖表/注冊人相關的異常(mysql超時)。 我了解此新注冊表未提交,因此在第二個ctx中,此注冊表不存在。
我已經嘗試過隔離級別= ReadUncommited。
public static int createSchedule(...){
using (TransactionScope transaction = new TransactionScope(
TransactionScopeOption.RequiresNew,
new TransactionOptions() {
I solationLevel = IsolationLevel.ReadUncommitted }))
{
var myId = createPerson(...);
using (var ctx = new MyAppDbEntity(MyConnStr))
{
Schedule sc = new Schedule{
Id = 1,
...
PersonId = myId,
...
};
//Logic code
ctx.Schedule.Add(sc);
ctx.saveChanges(); //Exception raised Here
transaction.Complete();
}
}
}
public static int createPerson(...){
using (var ctx = new GenericDbEntity(MyConnStr))
{
Person p = new Person{
Id = 10,
...
};
//Logic code
ctx.Person.Add(p);
ctx.saveChanges();
return p.Id;
}
}
有什么解決方案可以解決我的問題嗎?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.