Griffin.Data.Mapper.CommandBuilders.CommandBuilder.InsertCommand C# (CSharp) Method

InsertCommand() public method

Generate an insert command, should end with a command that returns the insert identity.
/// command /// or /// entity /// No values were added to the query for + entity
public InsertCommand ( IDbCommand command, object entity ) : void
command IDbCommand Command to add the query to
entity object Entity to store
return void
        public virtual void InsertCommand(IDbCommand command, object entity)
        {
            if (command == null) throw new ArgumentNullException("command");
            if (entity == null) throw new ArgumentNullException("entity");

            var columns = "";
            var values = "";
            foreach (var key in _keys)
            {
                if (key.IsAutoIncrement)
                    continue;

                var value = key.GetValue(entity);
                if (value == null || (TreatZeroAsNullForKeys && value.Equals(0)))
                    continue;
                columns += string.Format("{0}, ", key.ColumnName);
                values += string.Format("@{0}, ", key.PropertyName);
                command.AddParameter(key.PropertyName, value);
            }
            foreach (var prop in _values)
            {
                if (!prop.CanRead)
                    continue;

                var value = prop.GetValue(entity);
                columns += string.Format("{0}, ", prop.ColumnName);
                values += string.Format("@{0}, ", prop.PropertyName);
                command.AddParameter(prop.PropertyName, value ?? DBNull.Value);
            }
            if (command.Parameters.Count == 0)
                throw new DataException("No values were added to the query for " + entity);

            command.CommandText = string.Format("INSERT INTO {0} ({1}) VALUES({2})",
                TableName,
                columns.Remove(columns.Length - 2, 2),
                values.Remove(values.Length - 2, 2));
        }

Usage Example

        public void key_without_value_is_ignored_in_the_insert_query()
        {
            var mapper = Substitute.For<ICrudEntityMapper>();
            mapper.TableName.Returns("Users");
            mapper.Properties.Returns(new Dictionary<string, IPropertyMapping>
            {
                {"Id", new FakePropertyMapping("Id", "id"){IsPrimaryKey = true}}
            });
            var command = new AdoNetFakes.FakeCommand();
            var entity = new { Id = "Hello" };


            var sut = new CommandBuilder(mapper);
            Action actual =  () => sut.InsertCommand(command, entity);

            actual.ShouldThrow<DataException>();
        }
All Usage Examples Of Griffin.Data.Mapper.CommandBuilders.CommandBuilder::InsertCommand