问题
I'm trying to execute the following :
SqlConnection cnSql = new SqlConnection(cnstring);
cnSql.Open();
SqlTransaction Transactie = default(SqlTransaction);
Transactie = cnSql.BeginTransaction();
SqlCommand cmddelbonh = new SqlCommand();
cmddelbonh.Connection = Transactie.Connection;
cmddelbonh.Transaction = Transactie;
cmddelbonh.CommandText = "update artikelgroepen set OMSN='XXXXX' where ID = 3";
cmddelbonh.ExecuteNonQuery();
using (CXNACC_TESTFIRMA cxn = new CXNACC_TESTFIRMA(cnSql))
{
cxn.Database.UseTransaction(Transactie);
var myList = cxn.ARTIKELS.Take(100).ToList();
cxn.ARTIKELS.First().OMSN = "XXXXX";
cxn.SaveChanges();
}
Transactie.Commit();
This line cxn.Database.UseTransaction(Transactie); enters the OnModelCreating on the Context and throws a UnintentionalCodeFirstException
When commenting out the throw new UnintentionalCodeFirstException it works but I don't like having to comment out an error which shouldn't be triggered anyway.
I googled around, but found no answers as to how use the UseTransaction feature of EF6 in a databasefirst context.
Before you ask : the connectionString for Entity is present in the app.config.
Any thoughts on this please?
Thanks
回答1:
I found this article which explains a bit more about database-first vs code-first...
It seems that using the constructor taking the connection as parameter (your line: using (CXNACC_TESTFIRMA cxn = new CXNACC_TESTFIRMA(cnSql))
) will use code-first strategy to build the context
But then I was advised the following:
For EF to use the metadata from your EDMX file you need to pass in an EntityConnection rather than a straight up SqlConnection.
If you want the SqlConnection to be able to use for other tasks outside of the context then you can always create the EntityConnection and then grab the StoreConnection off it:
var entityConnection = new EntityConnection("name=AdventureWorksEntities");
var dbConnection = entityConnection.StoreConnection;
Because EntityConnection derives from DbConnection, you can still pass it into the same constructor on DbContext that you were trying to use.
来源:https://stackoverflow.com/questions/24605535/entity-framework-6-usetransaction-databasefirst-throws-unintentionalcodefirstexc