Put interface behind database provider for testing. Use state object to get data from database, then map to model.

This commit is contained in:
Robert Marshall 2019-04-14 21:49:01 +01:00
parent 5a0d0933ce
commit 20ccdd07f1
11 changed files with 118 additions and 34 deletions

View file

@ -2,21 +2,22 @@ using System.Threading.Tasks;
using System.Linq;
using Dapper;
using Website.Models;
using Website.Data.States;
namespace Website.Data
{
public class BlogRepository
{
private readonly DatabaseProvider _dbProvider;
private readonly IDatabaseProvider _dbProvider;
public BlogRepository(DatabaseProvider dbProvider) => _dbProvider = dbProvider;
public BlogRepository(IDatabaseProvider dbProvider) => _dbProvider = dbProvider;
public async Task<BlogPost> GetPostAsync(int id) {
const string query = "SELECT * FROM blog_posts WHERE post_id=@id";
const string query = "SELECT * FROM blog_posts WHERE post_id=@id AND post_deleted=0";
using (var connection = _dbProvider.NewConnection()) {
connection.Open();
var result = await connection.QueryAsync<BlogPost>(query, new{id});
return result.FirstOrDefault();
var result = await connection.QueryAsync<BlogPostState>(query, new{id});
return new BlogPost(result.First());
}
}
}

View file

@ -1,17 +0,0 @@
using System.Data;
using Microsoft.Extensions.Configuration;
using MySql.Data.MySqlClient;
namespace Website.Data
{
public class DatabaseProvider
{
private readonly string _connectionString;
public DatabaseProvider(IConfiguration config) => _connectionString = config.GetConnectionString("database");
public DatabaseProvider(string connectionString) => _connectionString = connectionString;
public IDbConnection NewConnection() => new MySqlConnection(_connectionString);
}
}

View file

@ -0,0 +1,9 @@
using System.Data;
namespace Website.Data
{
public interface IDatabaseProvider
{
IDbConnection NewConnection();
}
}

View file

@ -0,0 +1,17 @@
using System.Data;
using Microsoft.Extensions.Configuration;
using MySql.Data.MySqlClient;
namespace Website.Data
{
public class MySQLDatabaseProvider:IDatabaseProvider
{
private readonly string _connectionString;
public MySQLDatabaseProvider(IConfiguration config) => _connectionString = config.GetConnectionString("database");
public MySQLDatabaseProvider(string connectionString) => _connectionString = connectionString;
public IDbConnection NewConnection() => new MySqlConnection(_connectionString);
}
}

View file

@ -0,0 +1,19 @@
using System;
using Dapper.Contrib.Extensions;
namespace Website.Data.States
{
[Table("blog_posts")]
public class BlogPostState
{
[Key]
public int Post_Id { get; set; }
public string Post_Title { get; set; }
public string Post_Content { get; set; }
public DateTime Post_Timestamp { get; set; }
public string Post_Draft { get; set; }
public string Post_Url { get; set; }
public bool Post_Deleted{ get; set; }
public int User_Id { get; set; }
}
}