开发者

Using ReadOnlyCollection preventing me from setting up a bi-directional many-to-many relationship

开发者 https://www.devze.com 2022-12-25 05:17 出处:网络
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 pre

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> 开发者_如何学GoNetworks
    {
        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();
        }
    }
}


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号