简体   繁体   中英

Establishing Entity Framework Entity addition & ADO.Net stored procedure INSERTS together inside a single Transaction

I have an application where I am using Entity Framework or handle data from database tables. There is a main table, CUSTOMER which is is linked to 3 other tables through foreign keys. The linked tables are

RENTAL
PAYMENTS
VEHICLES

I am able to add / edit / delete entities on all these 4 tables using EF.

I would like to change the current scenario (where EF is used to handle all DB transaction) to something like this.

After I create a new entity and when try to save the entities (5 new entities/records) back to the database, I would like to use a stored procedure to add the new entity to VEHICLES model and use EF to save entities to all other models - and still gat all this down under one single transaction.

Also, I have to wait till the EF call is completed, since I need the new CUSTOMER_ID created as part of EF save to be passed on as an input parameter to the stored procedure to save VEHICLES entity.

I don't want to call the stored procedure from outside the transaction, thus if the Stored Procedure call fails, the changes made to the database through EF also are rolled back.

Anyone have any idea how to get this accomplished?

PS : Not looking for any code samples; a high level illustration will help.

I am using Entity Framework 5, .Net v4.5, VS 2013, Oracle 11g, ODP.Net

Map stored procs to Entity 1) Create the stored procedure(s) 2) Update your data model to include the stored procedure(s) - "Update Model From Database" menu via EF 6.x

3) Then find the Entity (or create a new Entity) in the Entity Data Model and hook up Stored Procs to Insert, Update, and Delete Functions - right click the Entity and select "Stored Procedure Mapping" menu

4) Use LinqToEntity to add/modify the entities with Database.BeginTransaction() then call SaveChanges() on context, then Commit or Rollback.

Note: Starting with EF6 Database.ExecuteSqlCommand() by default will wrap the command in a transaction if one was not already present. There are overloads of this method that allow you to override this behavior if you wish. Also in EF6 execution of stored procedures included in the model through APIs such as ObjectContext.ExecuteFunction() does the same (except that the default behavior cannot at the moment be overridden). In either case, the isolation level of the transaction is whatever isolation level the database provider considers its default setting. By default, for instance, on SQL Server this is READ COMMITTED. https://msdn.microsoft.com/en-us/data/dn456843.aspx

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM