Пример #1
0
        public void AddDepartmentToDb(Department department)
        {
            using (var connection = new SqlConnection(connectionString))
            {
                connection.Open();

                string countCommand = "SELECT COUNT(*) FROM Department WHERE Id=" + department.Id;
                SqlCommand sqlCountCommand = new SqlCommand(countCommand, connection);
                var count = (int)sqlCountCommand.ExecuteScalar();
                if (count >= 1)
                {
                    string updateCommand = "UPDATE Department SET Name=@name WHERE Id=" + department.Id;
                    AddOrEditDepartment(updateCommand, department, connection);
                }
                else
                {
                    string addCommand = "INSERT INTO Department (Name) VALUES (@name)";
                    AddOrEditDepartment(addCommand, department, connection);

                    SqlCommand getLastIdCmd = new SqlCommand("SELECT @@IDENTITY", connection);
                    int insertedRecordId = (int)(decimal)getLastIdCmd.ExecuteScalar();
                    department.Id = insertedRecordId;
                }
            }
        }
Пример #2
0
        private void AddOrEditDepartment(string command, Department department, SqlConnection connection)
        {
            SqlCommand sqlCommand = new SqlCommand(command, connection);
            sqlCommand.Parameters.AddWithValue("@name", department.Name);

            var rows = sqlCommand.ExecuteNonQuery();
            Console.WriteLine("Rows Affected: {0}", rows);
        }