Reputation: 324
I have a SaveClientDataMethod that will save, and according to my database first i have to save data To Address and Contacts table, and only than update or add Client. So here is my quastion, how to use DbContext object in such case? Shoulld I create context in each method, or only in root method or Use context as private property of class?
public class TestClass
{
private void SaveClientDataMethod()
{
using (var context = new TestEntities)
{
NewRecord.FK_1 = TestMethod1(context);
NewRecord.FK_2 = TestMethod2(context);
context.TestTable.Add(NewRecord);
context.SaveChanges();
}
}
private int SaveAddress(TestEntities context)
{
context.SaveChanges(); /// Saving some data and returning id of new record
return id;
}
private int SaveContacts(TestEntities context)
{
context.SaveChanges(); /// Saving some data and returning id of new record
return id;
}
}
Also in such way if exception would accurs in TestMethod2, part of transaction will be saved to database and that violates UoW pattern, please correct me if i'm wrong.
Upvotes: 0
Views: 173
Reputation: 1309
The answer is that you should have one context per unit of work. DbContext
is actually EF's implementation of UoW. Calling SaveChanges()
commits the UoW to the database. If any problem occurs while data is being updated, simply don't call SaveChanges()
and no change to the database will occur.
What this means in practice varies depending on what the environment is in which you're using EF. I write web applications, so typically I have one DbContext
per request, because typically a request is one UoW. In other environments things might be different.
Upvotes: 1