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.
c # transactions entity-framework-4 transactionscope
nighthawk457
source share