tags:

views:

35

answers:

1

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();
        }
    }
}
+2  A: 

You'll need to add some way of accessing the non-read only collection in Network from the outside of the class. You could add a public AddUser method to it, for instance. If you really don't want anyone accessing it besides you, you could use an internal method/property.

Matti Virkkunen
That's what I figured. Although there's still the risk now of someone calling network.AddUser(user) instead of user.JoinNetwork(network).
Kevin Pang