2016-04-21 24 views
0

我試圖向表中添加一個條目,並使用該添加條目的主鍵來創建另一個表中的附加條目。使用WCF事務插入到多個表

我得到的錯誤是

事務管理器已禁用其遠程/網絡 事務的支持。 (異常來自HRESULT:0x8004D024)

我相信這是由一個單一的TransactionScope內創建多個連接造成的,但我一個範圍內/ using語句做的一切,所以我不認爲我應該接受這個錯誤。

服務

[OperationBehavior(TransactionScopeRequired = true)] 
    public void CreateGroup(NewGroupData data) 
    { 
     var groupRepo = _GroupRepo ?? new InvestigatorGroupRepository(); 
     groupRepo.CreateGroup(data.UserId, data.InvestigatorGroupName, data.HasGameAssignment, data.InstitutionId); 

    } 

public void CreateGroup(string userId, string investigatorGroupName, bool hasGameAssignment, int institutionId) 
    { 
     using (var context = new GameDbContext()) 
     { 
      var newGroup = new InvestigatorGroup() 
      { 
       InvestigatorGroupName = investigatorGroupName, 
       HasGameAssignment = hasGameAssignment, 
       InstitutionId = institutionId, 
       IsTrashed = false 
      }; 

      int institutionUserId = 
       context.InstitutionUsers.Where(
        iu => !iu.IsTrashed && iu.APUser.UserId == userId && iu.InstitutionId == institutionId).Select(iu => iu.InstitutionUserId).Single(); 

      var newGroupUser = new InvestigatorGroupUser() 
      { 
       InstitutionUserId = institutionUserId, 
       InvestigatorGroup = newGroup, 
       CreationDate = DateTime.Now 
      }; 
      context.InvestigatorGroupUsers.Add(newGroupUser); 

      context.SaveChanges(); 
     } 
    } 

回答

1

開始時你有錯誤的假設。

線...

int newGroupId = context.InvestigatorGroups.Add(newGroup).InvestigatorGroupId; 

...將始終分配0到newGroupIdAdd方法只標記插入的實體,但不實際插入它。只有SaveChanges將數據寫入數據庫,而不是Entity Framework中的任何其他方法。

所以分配...

InvestigatorGroupId = newGroupId, 

...故障也是如此。你有新的InvestigatorGroup分配給導航屬性在InvestigatorGroupUser

InvestigatorGroup = newGroup, 

此導航屬性添加到InvestigatorGroupUser如果你還沒有得到它。

如果有,它足以執行這些行:

context.InvestigatorGroupUsers.Add(newGroupUser); 
context.SaveChanges(); 

無需AddnewGroup對象也將加入newGroupUser增加。

所以,如果你這樣做,你需要的唯一交易就是SaveChanges默認內部使用的交易。對於您顯示的代碼,您不需要TransactionScope。如果這是更大的WCF交易的一部分,故事可能會有所不同,但我認爲至少您需要理清一些誤解。

+0

感謝您的建議!我做了你所說的改變,但我仍然得到相同的錯誤(請參閱我更新的問題)。我保留了transactionscope,因爲如果對InvestigatorGroupUser的插入失敗,我希望插入InvestigatorGroup也會失敗 –

+0

問題是您不需要TransactionScope。 'SaveChanges'不會*在一個事務中插入*,它會自動啓動並提交。 –

+1

雖然@GertArnold是正確的,在這種情況下交易是不必要的,我相信http:// stackoverflow。com/questions/10130767/the-transaction-manager-has-disabled-its-support-for-remote-network-transactions將解釋如何解決這個錯誤,如果你在需要的情況下遇到它。 – dman2306