2013-10-11 44 views
0

我需要在MVC4項目的控制器中的實體框架控件(版本5)中使用事務。 這是因爲我已經在同一個事務中在不同的表中的數據保存,並避免數據不一致..DbContext不包含使用事務實體框架的'連接'錯誤的定義

using System; 
using System.Collections.Generic; 
using System.Linq; using System.Web.Mvc; 
using System.IO; 
using System.Web.UI.WebControls; 
using System.Web.UI; 
using System.Data; 
using System.Data.Objects; 

private DBcontextName context = new DBcontextName(); 

context.Connection.Open(); 

當我嘗試使用事務,對象連接不被認可的背景下

的DbContext做不包含「連接」的定義,也沒有接受類型的第一個參數的擴展方法「連接」...

我不明白它是什麼問題, 你能幫助我嗎?

namespace NameSpaceName { 
    using System; 
    using System.Data.Entity; 
    using System.Data.Entity.Infrastructure; 
    using System.Data.Objects; 
    using System.Data.Objects.DataClasses; 
    using System.Linq; 

    public partial class DBcontextName : DbContext 
    { 
     public DBcontextName() 
      : base("name=DBcontextName ") 
     { 
     } 

     protected override void OnModelCreating(DbModelBuilder modelBuilder) 
     { 
      throw new UnintentionalCodeFirstException(); 
     } 

     public DbSet......{ get; set; } 
     public DbSet......{ get; set; } 

       } 
} 

感謝

回答

2

嘗試這樣的:

using (TransactionScope scope = new TransactionScope()) 
{ 
    using (DBcontextName context = new DBcontextName() 
    { 
     SqlConnection connection = (SqlConnection)((EntityConnection)context.ObjectContext.Connection).StoreConnection; 

      using (SqlCommand command = storeConnection.CreateCommand()) 
      { 
       command.Connection = connection ; 
       connection.Open(); 

       command.CommandText = yourStoredProcedureName; 
       command.CommandType = CommandType.StoredProcedure; 
       command.Parameters.AddRange(yourSqlParameters); 

       using (DbDataReader reader = command.ExecuteReader()) 
       { 
        // Do stuff 
       } 
      } 
    } 
    scope.Complete(); 
} 

你只需要做到這一點,如果你儘管調用存儲過程(與多個記錄的速度,你可以有一個PROC回吐一個用於保存記錄列表的表值參數)。如果你只是想使用實體框架,你可以這樣做:

using (TransactionScope scope = new TransactionScope()) 
{ 
    using (DBcontextName context = new DBcontextName() 
    { 
     // Get objects, delete objects, add objects, etc. 
     // Or add new objects 
     context.SaveChanges(); 
    } 
    scope.Complete(); 
} 
+0

謝謝你,我可以使用事務範圍內,如果我不得不做多個保存更改(從一個表中獲取身份,並在另一個使用它) ?如何在錯誤情況下回滾? – user2743368

+0

是的,你可以。對不起,我忘了在TransactionScope using語句的末尾添加對scope.Complete()的調用,這將表明您已完成並希望提交事務。在這一點之前發生的任何錯誤都會導致事務回滾。這是假設交易範圍創建了交易(在這種情況下它將具有)。這裏是一些關於TransactionScope.Complete()和錯誤處理的更多文檔,包括一個例子:http://msdn.microsoft.com/en-gb/library/system.transactions.transactionscope.complete.aspx – mayabelle

相關問題