2013-10-11 45 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

相关问题