WriteEatSleepRepeat
WriteEatSleepRepeat

Reputation: 3143

many to many unidirectional

I have a many to many relationship between User and Survey, the relationship is bi-directional, so when adding a new survey for a list of users, I need to do this:

foreach(User user in users)
{
    survey.Users.Add(user);
    user.Survey.Add(survey);
}

Iterating through all of the users looks overkill to me as there can be many users.

Isn't there a better way? Is it possible to have a unidirectional many to many?

Upvotes: 1

Views: 640

Answers (2)

Jamie Ide
Jamie Ide

Reputation: 49301

Yes, you can have a unidirectional many-to-many. There's nothing special you need to do to achieve this, just do not map the other side of the relationship.

If you need to maintain an in-memory representation of the relationship, then you need to add the references to both sides of the relationship as you're doing. This isn't overkill, you have to associate a set of users with a survey so at some point you have to loop through the set of users and make that association.

If you want to avoid loading the survey's user collection, you can check if the collection is initialized before accessing it:

foreach(User user in users)
{
    user.Survey.Add(survey);
    if (NHibernateUtil.IsInitialized(survey.Users)
    {
        survey.Users.Add(user);
    }
}

Upvotes: 0

Mathew Thompson
Mathew Thompson

Reputation: 56459

Ah, your problem is your database design. Many-to-many relationships will cause you major headaches like this if they aren't decomposed :).

Solution: Create a new table called UserSurvey, with a Primary Key and then a UserID field and a SurveyID field, like so:

----------------------------------------
| UserSurveyID | PrimaryKey            |
| UserID       | Foreign Key to User   |
| SurveyID     | Foreign key to Survey |
----------------------------------------

Then all you need to do is query that table for what you need.

What I would also do is maybe in the nHibernate UserSurvey class, put the actual User property and the Survey property to save you additional querying once you have your UserSurvey objects.

Upvotes: 1

Related Questions