Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -118,3 +118,4 @@
/BlogWebApp/Tests/Blog.ServicesTests/bin/Debug/net10.0
/BlogWebApp/Tests/Blog.UnitTests/bin/Debug/net10.0
/Sdk/Blog.Sdk.ExampleUsage/bin/Debug/net10.0
/BlogWebApp/Aspire/Blog.Aspire/Blog.Aspire.AppHost/bin/Debug/net10.0
Original file line number Diff line number Diff line change
@@ -1,32 +1,35 @@
namespace Blog.Web.StartupConfigureServicesInstallers;
Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

test

using Blog.EntityServices.DapperServices.Interfaces;

using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
namespace Blog.Web.StartupConfigureServicesInstallers;

using Blog.EntityServices.DapperServices;
using Blog.Services.Core.Caching;
using Blog.Services.Core.Caching.Interfaces;
using Blog.Services.Core.Email.Templates;
using Blog.Services.Core.Security;
using CommonServices;
using CommonServices.EmailServices;
using CommonServices.EmailServices.Interfaces;
using CommonServices.Interfaces;
using Core;
using Core.Configuration;
using Core.Infrastructure;
using Core.Interfaces;
using Data;
using Data.Models;
using Data.Repository;
using Blog.Services.Core.Caching;
using Blog.Services.Core.Caching.Interfaces;
using Blog.Services.Core.Email.Templates;
using Blog.Services.Core.Security;
using CommonServices;
using CommonServices.EmailServices;
using CommonServices.Interfaces;
using EntityServices.ControllerContext;
using EntityServices.Interfaces;
using EntityServices.EntityFrameworkServices;
using EntityServices.EntityFrameworkServices.Identity.Auth;
using EntityServices.EntityFrameworkServices.Identity.RefreshToken;
using EntityServices.EntityFrameworkServices.Identity.Registration;
using EntityServices.EntityFrameworkServices.Identity.User;
using EntityServices.Interfaces;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;

/// <summary>
/// Application services installer.
Expand Down Expand Up @@ -71,5 +74,13 @@ public void InstallServices(IServiceCollection services, IConfiguration configur
services.AddTransient<IPostsTagsRelationsService, PostsTagsRelationsService>();

services.AddTransient<IResponseCacheService, ResponseCacheService>();

// Dapper services
services.AddTransient<IPostsDapperService, PostsDapperService>();
services.AddTransient<ICommentsDapperService, CommentsDapperService>();
services.AddTransient<IProfileDapperService, ProfileDapperService>();
services.AddTransient<IMessagesDapperService, MessagesDapperService>();
services.AddTransient<ITagsDapperService, TagsDapperService>();
services.AddTransient<IPostsTagsRelationsDapperService, PostsTagsRelationsDapperService>();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -26,5 +26,13 @@ public void InstallServices(IServiceCollection services, IConfiguration configur
services.AddTransient<IRepository<Message>, Repository<Message>>();
services.AddTransient<IRepository<Tag>, Repository<Tag>>();
services.AddTransient<IRepository<PostsTagsRelations>, Repository<PostsTagsRelations>>();

// Dapper repositories
services.AddTransient<IDapperRepository<Post>, DapperRepository<Post>>();
services.AddTransient<IDapperRepository<Comment>, DapperRepository<Comment>>();
services.AddTransient<IDapperRepository<Profile>, DapperRepository<Profile>>();
services.AddTransient<IDapperRepository<Message>, DapperRepository<Message>>();
services.AddTransient<IDapperRepository<Tag>, DapperRepository<Tag>>();
services.AddTransient<IDapperRepository<PostsTagsRelations>, DapperRepository<PostsTagsRelations>>();
}
}
1 change: 1 addition & 0 deletions BlogWebApp/Data/Blog.Data/Blog.Data.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
</ItemGroup>

<ItemGroup>
<PackageReference Include="Dapper" Version="2.1.66" />
<PackageReference Include="EntityFrameworkCore.Data.AutoHistory" Version="9.0.0" />
<PackageReference Include="Microsoft.AspNetCore.Identity.EntityFrameworkCore" Version="10.0.3" />
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="10.0.3" />
Expand Down
92 changes: 92 additions & 0 deletions BlogWebApp/Data/Blog.Data/DapperRepository.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
// <copyright file="DapperRepository.cs" company="Blog">
// Copyright (c) Blog. All rights reserved.
// </copyright>

using Blog.Core;
using Blog.Core.Infrastructure.Pagination;
using Blog.Data.Extensions;
using Blog.Data.Repository;
using Dapper;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Threading.Tasks;

namespace Blog.Data;

/// <summary>
/// Dapper repository.
/// </summary>
/// <typeparam name="T">IEntity.</typeparam>
public class DapperRepository<T>(IDbConnection connection)
: IDapperRepository<T>
where T : class, IEntity
{
/// <summary>
/// The table name.
/// </summary>
private readonly string _tableName = typeof(T).Name;

/// <inheritdoc cref="IRepository{TEntity}"/>
public async Task<IEnumerable<T>> GetAllAsync()
=> await connection.QueryAsync<T>($"SELECT * FROM {_tableName}");

/// <inheritdoc cref="IRepository{TEntity}"/>
public async Task<T?> GetByIdAsync(object id)
=> await connection.QueryFirstOrDefaultAsync<T>(
$"SELECT * FROM {_tableName} WHERE Id = @Id", new { Id = id });

/// <inheritdoc cref="IRepository{TEntity}"/>
public async Task<int> InsertAsync(T entity)
{
var insertQuery = DapperSqlGenerator.GenerateInsert(entity, _tableName);

return await connection.ExecuteAsync(insertQuery.Sql, insertQuery.Params);
}

/// <inheritdoc cref="IRepository{TEntity}"/>
public async Task<int> UpdateAsync(T entity)
{
var updateQuery = DapperSqlGenerator.GenerateUpdate(entity, _tableName);

return await connection.ExecuteAsync(updateQuery.Sql, updateQuery.Params);
}

/// <inheritdoc cref="IRepository{TEntity}"/>
public async Task<int> DeleteAsync(object id)
=> await connection.ExecuteAsync(
$"DELETE FROM {_tableName} WHERE Id = @Id", new { Id = id });

/// <inheritdoc cref="IRepository{TEntity}"/>
public async Task<bool> AnyAsync(string whereClause, object? param = null)
=> await connection.ExecuteScalarAsync<int>(
$"SELECT COUNT(1) FROM {_tableName} WHERE {whereClause}", param) > 0;

/// <inheritdoc cref="IRepository{TEntity}"/>
public async Task<PagedListResult<T>> SearchAsync(DapperSearchQuery query)
{
var where = string.IsNullOrWhiteSpace(query.WhereClause) ? string.Empty : $"WHERE {query.WhereClause}";
var order = string.IsNullOrWhiteSpace(query.OrderBy) ? string.Empty : $"ORDER BY {query.OrderBy}";

var sqlCount = $"SELECT COUNT(1) FROM {_tableName} {where}";
var total = await connection.ExecuteScalarAsync<int>(sqlCount, query.Parameters);

var sql = $"""
SELECT * FROM {_tableName}
{where}
{order}
OFFSET @Skip ROWS FETCH NEXT @Take ROWS ONLY
""";

var data = await connection.QueryAsync<T>(sql,
new { query.Skip, query.Take, query.Parameters });

return new PagedListResult<T>
{
Entities = data.ToList(),
Count = total,
HasNext = query.Skip + query.Take < total,
HasPrevious = query.Skip > 0
};
}
}
52 changes: 52 additions & 0 deletions BlogWebApp/Data/Blog.Data/Extensions/DapperSqlGenerator.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
// <copyright file="DapperSqlGenerator.cs" company="Blog">
// Copyright (c) Blog. All rights reserved.
// </copyright>

using System.Linq;

namespace Blog.Data.Extensions;

/// <summary>
/// Dapper Sql generator.
/// </summary>s
public static class DapperSqlGenerator
{
/// <summary>
/// Generate insert.
/// </summary>
/// <param name="entity">The entity.</param>
/// <param name="table">The table.</param>
/// <returns>The Sql string.</returns>
/// <returns>The params.</returns>
public static (string Sql, object Params) GenerateInsert<T>(T entity, string table)
{
var props = typeof(T).GetProperties()
.Where(p => p.Name != "Id");

var columns = string.Join(",", props.Select(p => p.Name));
var values = string.Join(",", props.Select(p => "@" + p.Name));

var sql = $"INSERT INTO {table} ({columns}) VALUES ({values})";

return (sql, entity);
}

/// <summary>
/// Generate update.
/// </summary>
/// <param name="entity">The entity.</param>
/// <param name="table">The table.</param>
/// <returns>The Sql string.</returns>
/// <returns>The params.</returns>
public static (string Sql, object Params) GenerateUpdate<T>(T entity, string table)
{
var props = typeof(T).GetProperties()
.Where(p => p.Name != "Id");

var setClause = string.Join(",", props.Select(p => $"{p.Name} = @{p.Name}"));

var sql = $"UPDATE {table} SET {setClause} WHERE Id = @Id";

return (sql, entity);
}
}
67 changes: 67 additions & 0 deletions BlogWebApp/Data/Blog.Data/Repository/IDapperRepository.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
// <copyright file="IDapperRepository.cs" company="PlaceholderCompany">
// Copyright (c) PlaceholderCompany. All rights reserved.
// </copyright>

using System.Collections.Generic;
using System.Threading.Tasks;
using Blog.Core;
using Blog.Core.Infrastructure.Pagination;

namespace Blog.Data.Repository;

/// <summary>
/// Dapper repository interface.
/// </summary>
/// <typeparam name="T">Type.</typeparam>
public interface IDapperRepository<T>
where T : IEntity
{
/// <summary>
/// Gets all asynchronous.
/// </summary>
/// <returns>Type.</returns>
Task<IEnumerable<T>> GetAllAsync();

/// <summary>
/// Async get item by id async.
/// </summary>
/// <param name="id">id.</param>
/// <returns>Task.</returns>
Task<T?> GetByIdAsync(object id);

/// <summary>
/// Inserts the asynchronous.
/// </summary>
/// <param name="entity">The entity.</param>
/// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns>
Task<int> InsertAsync(T entity);

/// <summary>
/// Updates the asynchronous.
/// </summary>
/// <param name="entity">The entity.</param>
/// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns>
Task<int> UpdateAsync(T entity);

/// <summary>
/// Deletes the asynchronous.
/// </summary>
/// <param name="id">The identifier.</param>
/// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns>
Task<int> DeleteAsync(object id);

/// <summary>
/// Asynchronous check on any.
/// </summary>
/// <param name="whereClause">The where clause.</param>
/// <param name="param">The parameter.</param>
/// <returns>Task.</returns>
Task<bool> AnyAsync(string whereClause, object? param = null);

/// <summary>
/// Async search.
/// </summary>
/// <param name="query">The query.</param>
/// <returns>Task.</returns>
Task<PagedListResult<T>> SearchAsync(DapperSearchQuery query);
}
Loading
Loading