コード例 #1
0
        private void MakeFriends( User first, User second, MongoCollection userCollection )
        {
            var firstFriend = new Friend( first );
            var secondFriend = new Friend( second );

            // Add permanently to model without saving
            first.Friends.Add( secondFriend );
            second.Friends.Add( firstFriend );

            // Add atomically to database
            userCollection.Update( Query.EQ( IdFieldName, first.Id ),
                                  Update.AddToSet( FriendsFieldName,
                                                  secondFriend.ToBsonDocument() ) );

            userCollection.Update( Query.EQ( IdFieldName, second.Id ),
                                  Update.AddToSet( FriendsFieldName,
                                                  firstFriend.ToBsonDocument() ) );

            // Update favorite movie collections for two users
            userCollection.Update( Query.EQ( IdFieldName, first.Id ),
                                  Update.AddToSetEachWrapped(
                                      FriendsFavoriteMoviesFieldName,
                                      (IEnumerable<MovieShortDetail>)second.FavoriteMovies ) ); /* We need this explicit type cast because driver
                                                                                                * wrong interpret ICollection and added whole
                                                                                                * collection as one element. */
            userCollection.Update( Query.EQ( IdFieldName, second.Id ),
                                  Update.AddToSetEachWrapped(
                                      FriendsFavoriteMoviesFieldName,
                                      (IEnumerable<MovieShortDetail>)first.FavoriteMovies ) );
        }