1

I need to use a transaction in Entity Framewok (version 5) in a controller of an MVC4 project. This because I've to save data in different table within the same transaction and avoid data inconsistency..

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();

When i try to use transaction, the object Connection is not recognized by context

DbContext does not contain a definition for 'Connection' and no extension method 'Connection' accepting a first argument of type...

I don't understand what it's wrong, can you help me please?

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; }

               }
}

Thanks

4

1 回答 1

2

Try like this:

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();
}

You only need to do this if you are calling a stored procedure though (for speed with multiple records, you could have a proc taking a table-valued parameter to save a list of records). If you just want to use entity framework, you can do this:

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();
}
于 2013-10-11T15:29:23.710 回答