Understanding Transactions in Entity Infrastructure

Hi, I am trying to use transactions with Entity Framework. With so much information available on the Internet on various ways of conducting transactions, I must say that I am a little confused correctly. I have an example database with two tables Employee and Company. The Employee table has a foreign key related to the company identifier. Given that I want to implement a transaction in which I insert an entry into the Company table and then an entry into the Employee table, and I want to do this so that the records are inserted only if both of them are successful. I have the following code.
public void addCompanyToDatabase() { using (var context = new myTestEntities()) { context.Connection.Open(); //added this as was getting the underlying //provider failed to open using (TransactionScope scope = new TransactionScope()) { try { Company c = new Company(); c.Name = "xyz"; context.Companies.AddObject(c); context.SaveChanges(); //int a = 0; //int b = 5 / a; Employee e = new Employee(); e.Age = 15; e.Name = "James"; e.CompanyId = c.Id; context.Employees.AddObject(e); context.SaveChanges(); scope.Complete(); } catch (Exception ex) { Console.WriteLine("Exception Occurred"); } } } } 

I wanted to know if this was the right way to transact. If this is what uses the SaveChanges(false) and scope.AcceptAllChanges() functions. Any information would be helpful.

+8
c # transactions entity-framework-4 transactionscope
source share
2 answers

In your case, you do not need to manage any connection or transaction: Entity Framework will do it for you. If you did not provide EF with an open connection (but with a connection string), it will open the connection and begin the transaction during a call to context.SaveChanges() . When something fails during this call, the transaction will be canceled.

In other words, your method might look something like this:

 public void addCompanyToDatabase() { using (var context = new myTestEntities()) { Company c = new Company(); c.Name = "xyz"; context.Companies.AddObject(c); Employee e = new Employee(); e.Age = 15; e.Name = "James"; e.CompanyId = c.Id; context.Employees.AddObject(e); // Only call SaveChanges last. context.SaveChanges(); } } 
+14
source share

1 - this service (I think the transaction service) should be running in the client to support TransactionScope

2-It is useful if your application has towing or more databases and you want all databases to update transactional transactions (for example, the connection change string of your context).

3. When you have a database, it is better to use SaveChanges (), which internally implement the transaction.

0
source share

All Articles