コード例 #1
0
 public void Save(Product product)
 {
     if (product.Id > 0)
     {
         Update(product);
     }
     else
     {
         Insert(product);
     }
 }
コード例 #2
0
        private void Insert(Product product)
        {
            using (var command = _connection.CreateCommand())
            {
                command.CommandText = "insert into Products (Name, Description, Price, CategoryCode) values (@Name, @Description, @Price, @CategoryCode);SELECT SCOPE_IDENTITY()";

                addDataColumnsParams(product, command);

                var id = command.ExecuteScalar();
                if (id != null)
                {
                    product.Id = Convert.ToInt32(id);
                }
                else
                {
                    throw new Exception("Insert error");
                }
            }
        }
コード例 #3
0
        private void Update(Product product)
        {
            using (var command = _connection.CreateCommand())
            {
                command.CommandText = "update Products set Name = @Name, Description = @Description, Price = @Price, CategoryCode = @CategoryCode where Id = @Id";
                addPKColumnParam(product.Id, command);
                addDataColumnsParams(product, command);

                if (command.ExecuteNonQuery() != 1)
                {
                    throw new Exception("Update error: Object not found");
                }
            }
        }
コード例 #4
0
 private static void addDataColumnsParams(Product product, SqlCommand command)
 {
     command.Parameters.AddWithValue("@Name", product.Name);
     command.Parameters.AddWithValue("@Description", string.IsNullOrEmpty(product.Description) ? DBNull.Value : (object)product.Description);
     command.Parameters.AddWithValue("@Price", product.Price);
     command.Parameters.AddWithValue("@CategoryCode", product.CategoryCode);
 }
コード例 #5
0
 public void Delete(Product product)
 {
     Delete(product.Id);
 }