Hello there,
I wrote following code to insert a data row and returning the ID of
the new row:
public int InsertDataRow(string tableName, IDictionary
columnValues, out object idValue)
{
idValue = 0;
IDbConnection conn = GetConnection();
try
{
string fields = null;
foreach (DictionaryEntry item in columnValues)
if (!_factory.IsGeometryValue(item.Value))
fields += item.Key.ToString() + ",";
if (fields.EndsWith(","))
fields = fields.Substring(0, fields.Length - 1);
string sql = "SELECT " + fields + " FROM " + tableName
+ " WHERE 0=1";
IDbCommand selectcmd = _factory.CreateCommand(sql,
conn);
selectcmd.Transaction = _transaction;
IDbCommand insertcmd = CreateInsertCommand
(tableName, columnValues, conn, true);
try
{
IDbDataAdapter dataAdapter =
_factory.CreateAdapter(selectcmd);
dataAdapter.InsertCommand = insertcmd;
DataSet dataSet = new DataSet();
dataAdapter.Fill(dataSet);
DataTable dataTable = dataSet.Tables[0];
DataRow dataRow = dataTable.NewRow();
foreach (DictionaryEntry item in columnValues)
dataRow[item.Key.ToString()] = item.Value;
dataTable.Rows.Add(dataRow);
int affectedrows = dataAdapter.Update(dataSet);
idValue = dataRow[idName];
return affectedrows;
}
catch (Exception ex)
{
Rollback();
throw CreateDataException
(ex, "Error inserting data row!\n" +
insertcmd.CommandText,
tableName, columnValues, true);
}
}
finally
{
CloseConnection(conn);
}
}
That works very fine, but I've got a problem inserting a value, which
is of userdefined type. In Oracle this could be the Oracle Spatial
type MDSYS.SDO_GEOMETRY.
Columns containing userdefined types cannot be selected.
e.g. "SELECT ID, SDOGEOMETRY FROM Table" would raise an error.
As you see in the upper code, I cannot easily insert an userdefined
type because I have to select the column with the userdefined type.
My trick is not to select the column of userdefined type, but to
specify it in the INSERT statement like this
SelectCommand = "SELECT ID FROM Table"
InsertCommand = "INSERT INTO Table (ID, SDOGEOMETRY) VALUES
p0,
MDSYS.SDO_GEOMETRY(...))"
I thought that it would work to specify the geometry (userdefined
value) hard-coded without any parameter. But I've got no chance: It is
not possible to specify a column in the INSERT statement, which does
not exist in the SELECT command.
Has anyone an idea how to insert a value of userdefined type into a
table by using the SelectCommand and InsertCommand properties of a
data adapter?
Regards,
Norbert