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