user3188370
user3188370

Reputation: 117

save in simple table and many-to-many relationship table in one transaction Entity Framework

Hello I have table in MS SQL for example:

Employee(
id int primary key identity(1,1),
firstName nvarchar(50),
lastName nvarchar(50),


)

and many-to many relationship table

    ordersEmployee(
    id int primary key identity(1,1)
    order_id int foreign key references order(id),
    employee_id int foreign key references employee(id),
   )

I'm using entity framework and I want to save new employee in Employees table and that's employee's id in ordersEmployee table in single transaction how could i do that?

Upvotes: 1

Views: 89

Answers (1)

meziantou
meziantou

Reputation: 21377

SaveChanges creates a transaction. If you have to call SaveChanges twice (or more) you can use a TransactionScope

using(var tx = new TransactionScope())
{
    // ...
    context.SaveChanges();
    // ...
    context.SaveChanges();

    tx.Complete();
}

Upvotes: 1

Related Questions