I am using the adapter model.
Suppose I have the typical User, UserRole, Role model, where UserRole is a m:n join table. Further, in my generated UserEntity class, I have the UserRoleCollection and the readonly m:n RoleCollection. My question is: What is the best way to keep these collections in sync? Specifically, assume I do the following:
- Fetch a UserEntity, prefetching both collections.
- Add an UserRole to the join collection
- Save the UserEntity recursively
<< ========================>>
Now, the RoleCollection of the UserEntity is out of sync. Trying to simply refetch the RoleCollection doesn't work. Because it is read only, I can't do anything to the collection. So the question is, what is the least amount of work I can do to get this read-only collection in sync? At the moment, I'm setting it to null, and refetching, which can't be the best way.
Thought? Thanks all! Appreciate the input as always. (I've included the test case below, which presupposes a _roles entity that contains a collection of all of the available roles. The function: TestCollections_AfterSave_Reset_AfterBothFetch(); simply creates a user, adds the UserRole items, saves the user and the userroles. Then it sets the user to null, and refetches it, along with both collections.)
[Test]
public void TestRemoveItemsFromCollection()
{
DataAccessAdapter adapter = new DataAccessAdapter();
/// Save the entity, and then refetch both collections
TestCollections_AfterSave_Reset_AfterBothFetch();
// Remove item from join collection doesn't remove the item from the m:n collection
UserRoleEntity userRoleToDelete = (UserRoleEntity) _userAll.UserRoleCollection[2];
_userAll.UserRoleCollection.RemoveAt(2);
adapter.DeleteEntity(userRoleToDelete);
Assert.AreEqual(_userAll.UserRoleCollection.Count, _roles.Count-1);
Assert.AreEqual(_userAll.RoleCollectionViaUserRole.Count, _roles.Count);
// Save the collection, and refetch both collections
adapter.SaveEntity(_userAll, true, true);
Assert.AreEqual(_userAll.UserRoleCollection.Count, _roles.Count-1);
Assert.AreEqual(_userAll.RoleCollectionViaUserRole.Count, _roles.Count);
// Now refetch both collections, and see if the other data is overwritten or not.
PrefetchPath2 prefetchWithBoth = new PrefetchPath2((int)EntityType.UserEntity);
prefetchWithBoth.Add(UserEntity.PrefetchPathRoleCollectionViaUserRole);
prefetchWithBoth.Add(UserEntity.PrefetchPathUserRoleCollection);
adapter.FetchEntity(_userAll, prefetchWithBoth);
Assert.AreEqual(_userAll.UserRoleCollection.Count, _roles.Count-1);
Assert.AreEqual(_userAll.RoleCollectionViaUserRole.Count, _roles.Count);
// Now refetch both collections, and see if the other data is overwritten or not.
adapter.FetchEntity(_userAll, prefetchWithBoth);
Assert.AreEqual(_userAll.UserRoleCollection.Count, _roles.Count-1);
Assert.AreEqual(_userAll.RoleCollectionViaUserRole.Count, _roles.Count-1);
}