Last active
February 26, 2020 18:37
-
-
Save rommsen/08a36bdd3c925129f96df8a26ec79bba to your computer and use it in GitHub Desktop.
Practical DDD Step 2 - Repositories
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Data.SqlClient; | |
namespace ddd_patterns | |
{ | |
public class OnlineTickets | |
{ | |
private readonly string _connectionString; | |
public OnlineTickets(string connectionString) | |
{ | |
_connectionString = connectionString; | |
} | |
public Guid AddTicket(Guid attendee) | |
{ | |
var availableTickets = GetAvailableTickets(); | |
if (availableTickets <= 0) | |
{ | |
throw new Exception("No Ticket available"); | |
} | |
return InsertTicket(attendee); | |
} | |
private int GetAvailableTickets() | |
{ | |
var availableTickets = 0; | |
const string sql1 = @"SELECT get number of available tickets from db"; | |
using var connection = new SqlConnection(_connectionString); | |
var command = new SqlCommand(sql1, connection); | |
connection.Open(); | |
var reader = command.ExecuteReader(); | |
while (reader.Read()) | |
{ | |
availableTickets = reader.GetInt32(0); | |
} | |
reader.Close(); | |
return availableTickets; | |
} | |
private Guid InsertTicket(Guid attendee) | |
{ | |
using var connection = new SqlConnection(_connectionString); | |
var tId = Guid.NewGuid(); | |
const string sql2 = @"Insert into tickets... tId = @tId, aId = @aId"; | |
var command2 = new SqlCommand(sql2, connection); | |
command2.Parameters.AddWithValue("@tId", tId); | |
command2.Parameters.AddWithValue("@tad", attendee); | |
command2.ExecuteNonQuery(); | |
return tId; | |
} | |
public void RemoveTicket(Guid ticket) | |
{ | |
using var connection = new SqlConnection(_connectionString); | |
const string sql = @"Delete FROM tickets WHERE tId = @tId"; | |
var command = new SqlCommand(sql, connection); | |
command.Parameters.AddWithValue("@tId", ticket); | |
command.ExecuteNonQuery(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment