i’m very new to the repository pattern, but so far i like how i can use it. I found this implementation on codeplex. My questions now are:
am i using the repository pattern in the correct manner?
and
can anyone provide a better solution for my example beneath?
Here is an example (i’m using poco) where i have fetched a location with lazyloading turned off earlier in the process. After some ui interaction i want to update the location properties (eg. name) and the related users (including add and remove):
using (var repo = RepositoryHelper.GetLocationRepository())
using (var repo2 = RepositoryHelper.GetUserRepository(repo.UnitOfWork))
{
repo.Add(location);
repo.UnitOfWork.Context.ObjectStateManager.ChangeObjectState(location, EntityState.Modified);
foreach (var user in location.Users)
{
repo2.Add(user);
if (user.Id != 0)
{
repo2.UnitOfWork.Context.ObjectStateManager.ChangeObjectState(user, EntityState.Unchanged);
}
}
foreach (var user in _remove.Where(user => user.Id != 0))
{
repo2.Delete(user);
}
repo2.UnitOfWork.Commit();
}
The example is working, although i’m very confused about how to the the Attach command. I thought it is used if the object comes from another context?! But if i try that, i always get an exception, that the object is in use by another context. And lets say, i’m detaching the location, i cannot access the Users collection right after that.
Another question (and i think it’s closly related to this): i’ve always read, that the database connection should be as short as possible. Therefor i added the IDisposable interface to the repositories, so i can use them in the same way as an ObjectContext. However i found some examples (i think also in the wpf application framework), where this is not the usual approach. So, what words should i follow?
Kind Regards,
matt
The key question: Why do you want to use repository and unit of work (UoW) patterns?
People usually use these patterns to separate EF code to internal repository and UoW implementation. Because of that upper layers will be completely independent on EF.
Your implementation doesn’t provide this separation. It is just a strange wrapper around
ObjectContextandObjectSet. In such case you don’t need repository and UoW at all and you can use EF classes directly. Even with EF classes you can still make your code testable (another wrong reason why people sometimes introduce repositories and UoW).To your second question. Lifetime of
ObjectContextshould be short as possible but it doesn’t mean that you should create new context for each query.ObjectContexthandles connection internally and it opens it only when it is needed. The reason why ObjectContext should be used for short period of time is because it also implements UoW pattern and moreover IdentityMap patterns (I described implications here). In WPF applicationObjectContextusually lives as long as the window or control presenting data for modification.