示例#1
0
        private static object Insert(this DbConnection connection, object data, string tableName,
                                     IFieldInfoCollection fields, DbTransaction transaction = null,
                                     OnConflictOption option                = OnConflictOption.Default,
                                     ICommandBuilder commandBuilder         = null,
                                     IExceptionProcessor exceptionProcessor = null,
                                     object keyValue      = null,
                                     bool persistKeyvalue = true)
        {
            if (data == null)
            {
                throw new ArgumentNullException("data");
            }

            commandBuilder = commandBuilder ?? DefaultCommandBuilder;

            using (var command = connection.CreateCommand())
            {
                commandBuilder.BuildInsert(command, data, tableName, fields,
                                           option: option,
                                           keyValue: keyValue,
                                           persistKeyvalue: persistKeyvalue);

                try
                {
                    var ptData = data as IPersistanceTracking;

                    ptData?.OnInserting();
                    var id = command.ExecuteScalar();
                    ptData?.OnInserted();

                    var pkField = fields.PrimaryKeyField;
                    if (pkField != null)
                    {
                        var value = ValueMapper.ProcessValue(pkField.RunTimeType, id);
                        pkField.SetFieldValue(data, value);

                        return(value);
                    }
                    else
                    {
                        return(id);
                    }
                }
                catch (Exception ex)
                {
                    if (exceptionProcessor is null)
                    {
                        throw;
                    }
                    else
                    {
                        throw exceptionProcessor.ProcessException(ex, connection, (string)null, transaction);
                    }
                }
            }
        }