public function save($object)
    {
        $this->assertObjectInstance($object);

        $state = $this->getState($object);
        if ($state->isReadOnly()) {
            return null;
        }

        $relationsIterator = new \ArrayIterator($this->getRelations());

        $modifiedManyManyRelations = $this->handleManyManyRelations($state, $relationsIterator);
        $this->handleHasManyRelations($state, $relationsIterator);
        $this->handleHasOneRelations($state, $relationsIterator);

        switch ($state->getObjectState()) {
            case EntityState::STATE_NEW:
                $primaryKey = $this->insert($object);
                break;

            case EntityState::STATE_NEW_WITH_PRIMARY_KEY:
                $pkField    = $this->getPrimaryKey();
                $primaryKey = $state->getOriginalFieldData($pkField);

                //Check if the record exists in the database
                if ($this->exists($primaryKey)) {
                    //We may have no way of knowing what has changed, but assume that the primary key hasn't
                    //Let's assume that the original data is actually all new
                    $data = $this->toArray($object);

                    //But only update the primary key if it really has changed
                    if ($data[ $pkField ] === $primaryKey) {
                        unset($data[ $pkField ]);
                    }

                    $primaryKey = $this->update($object, $data);
                } else {
                    $primaryKey = $this->insert($object);
                }
                break;

            default:
                $data       = $state->getChangedFields();
                $primaryKey = $this->update($object, $data);
                break;
        }

        $state->setState(EntityState::STATE_HANDLED);
        $state->refreshOriginalData();

        $this->updateManyToManyRelations($modifiedManyManyRelations, $primaryKey);

        return $primaryKey;
    }