Forgive me I am not good at EF6. If I make some mistake . Please help me to correct it. Thanks.
Firstly I want to implement the business logic in my service layer like below.
public class userService
{
void createWithCommit(User user)
{
MyEntityContext db= new MyEntityContext ();
...
db.Users.add(user);//Add a new user entity
....
Work w = new Work();
...
db.Works.add(w);//Add a new work entity
db.savechanges();//commit the changes which will insert 2 new record . one is user . another is work.
}
}
But in some service class I want to call multiple others service method in one transaction like below.
class utilService
{
void update(SomeClass cls)
{
using (var tran=new TransactionScope())
{
userService userSvr= new userService();
userSvr.create();//this method already include a savechanges().
jobService jobSvr= new jobService();
jobSvr.update();//this method may include another savechanges().
tran.Complete();//I don't why EF6 doesn't have the Commit method. just has the Complete method.
}
}
}
So I can use it in the ASP.net MVC controller like below.
class SomeController
{
ActionResult index()
{
userService userSvr = new userService();
userSvr.createWithCommit();
}
ActionResult util()
{
utilService utilSvr = new utilService ();
userSvr.update(....);
}
}
So you can see my idea is I want to include multiple service method into one transaction. and each of the included service methods may or may not include the code SaveChanges()
(That means a transaction is committed. Right ?).
And you can see . In my test , I tried to use the TransactionScope
to include multiple service method into one transaction. I mean it in the method utilService.update()
. But It seems the TransactionScope
not work after the SaveChanges() is called
. So My question is :
Is there any possibility to implement it as my idea ? If there is . What kind of pattern should I apply ? (I heard of UOW and Repository pattern . Are they the solution? Thanks.)