public function insert($repository, $data)
    {
        $context = $this->getCommandContext();

        $context->data = $data;
        $context->repository = $repository;

        if ($this->getCommandChain()->run('before.insert', $context) !== false) {
            $vals = array();

            $this->_adapter->getConnection()->autocommit(false);

            $resources = $repository->getResources();

            foreach ($data as $column => $val) {
                $column = $resources->getColumn($column);
                $key = $column->resource->getAlias();
                if (!isset($vals[$key])) {
                    $vals[$key] = array();
                }

                $vals[$key][$this->quoteName($column->name)] = $this->quoteValue($val);
            }

            $main_insert_id = null;

            foreach ($resources as $resource) {
                //check if therre now columns to be saved then probably a second empty
                //table so lets create an empty record
                $columns = isset($vals[$resource->getAlias()]) ? array_keys($vals[$resource->getAlias()])   : array();
                $values = isset($vals[$resource->getAlias()]) ? array_values($vals[$resource->getAlias()]) : array();

                if ($resource !== $resources->main()) {
                    $link = $resource->getLink();
                    $columns[] = $link->child;
                    $values[] = $main_insert_id;
                }

                $query = 'INSERT INTO '.$this->_adapter->getTablePrefix().$resource->getName()
                         .'('.implode(', ', $columns).') VALUES ('.implode(', ', $values).')';

                $this->execute($query);

                if ($resource === $resources->main()) {
                    $main_insert_id = $this->_adapter->getInsertId();
                }
            }

            $this->_adapter->getConnection()->commit();
            $this->_adapter->getConnection()->autocommit(true);

            $context->result = $main_insert_id;

            $this->getCommandChain()->run('after.insert', $context);
        }

        return $context->result;
    }