Using ReadOnlyCollection preventing me from setting up a bi-directional many-to-many relationship
- by Kevin Pang
I'm using NHibernate to persist a many-to-many relation between Users and Networks. I've set up both the User and Network class as follows, exposing each's collections as ReadOnlyCollections to prevent direct access to the underlying lists. I'm trying to make sure that the only way a User can be added to a Network is by using its "JoinNetwork" function. However, I can't seem to figure out how to add the User to the Network's list of users since its collection is readonly.
public class User
{
private ISet<Network> _Networks = new HashedSet<Network>();
public ReadOnlyCollection<Network> Networks
{
get
{
return new List<Network>(_Networks).AsReadOnly();
}
}
public void JoinNetwork(Network network)
{
_Networks.Add(network);
// How do I add the current user to the Network's list of users?
}
}
public class Network
{
private ISet<User> _Users = new HashedSet<User>();
public ReadOnlyCollection<User> Users
{
get
{
return new List<User>(_Users).AsReadOnly();
}
}
}