Fix DetachedInstanceError for Agent instance

The stacktrace observed seems to hint to a
situation where a session is not properly
rolled back when duplicate agent entries are
found.

Since it is ok to deal with duplicates, the
addition of agents to the DB must be done
one by one, otherwise we go against the
ATOMICITY property of a transaction of all
or none. It's either that or I am barking at
the wrong tree.

This patch also added UT to cover affected
code.

Closes-bug: 1282421
Related-bug: 1282253

Change-Id: Ic5f77808cc10f885d67f5a9cf3b3836283692850
Merge "Fix DetachedInstanceError for Agent instance"