1
0
mirror of https://github.com/bitwarden/server synced 2025-12-24 12:13:17 +00:00
Files
server/src/Infrastructure.Dapper/Repositories/Repository.cs
Justin Baur bae03feffe Revert filescoped (#2227)
* Revert "Add git blame entry (#2226)"

This reverts commit 239286737d.

* Revert "Turn on file scoped namespaces (#2225)"

This reverts commit 34fb4cca2a.
2022-08-29 15:53:48 -04:00

96 lines
3.0 KiB
C#

using System.Data;
using System.Data.SqlClient;
using Bit.Core.Entities;
using Bit.Core.Repositories;
using Dapper;
namespace Bit.Infrastructure.Dapper.Repositories
{
public abstract class Repository<T, TId> : BaseRepository, IRepository<T, TId>
where TId : IEquatable<TId>
where T : class, ITableObject<TId>
{
public Repository(string connectionString, string readOnlyConnectionString,
string schema = null, string table = null)
: base(connectionString, readOnlyConnectionString)
{
if (!string.IsNullOrWhiteSpace(table))
{
Table = table;
}
if (!string.IsNullOrWhiteSpace(schema))
{
Schema = schema;
}
}
protected string Schema { get; private set; } = "dbo";
protected string Table { get; private set; } = typeof(T).Name;
public virtual async Task<T> GetByIdAsync(TId id)
{
using (var connection = new SqlConnection(ConnectionString))
{
var results = await connection.QueryAsync<T>(
$"[{Schema}].[{Table}_ReadById]",
new { Id = id },
commandType: CommandType.StoredProcedure);
return results.SingleOrDefault();
}
}
public virtual async Task<T> CreateAsync(T obj)
{
obj.SetNewId();
using (var connection = new SqlConnection(ConnectionString))
{
var parameters = new DynamicParameters();
parameters.AddDynamicParams(obj);
parameters.Add("Id", obj.Id, direction: ParameterDirection.InputOutput);
var results = await connection.ExecuteAsync(
$"[{Schema}].[{Table}_Create]",
parameters,
commandType: CommandType.StoredProcedure);
obj.Id = parameters.Get<TId>(nameof(obj.Id));
}
return obj;
}
public virtual async Task ReplaceAsync(T obj)
{
using (var connection = new SqlConnection(ConnectionString))
{
var results = await connection.ExecuteAsync(
$"[{Schema}].[{Table}_Update]",
obj,
commandType: CommandType.StoredProcedure);
}
}
public virtual async Task UpsertAsync(T obj)
{
if (obj.Id.Equals(default(TId)))
{
await CreateAsync(obj);
}
else
{
await ReplaceAsync(obj);
}
}
public virtual async Task DeleteAsync(T obj)
{
using (var connection = new SqlConnection(ConnectionString))
{
await connection.ExecuteAsync(
$"[{Schema}].[{Table}_DeleteById]",
new { Id = obj.Id },
commandType: CommandType.StoredProcedure);
}
}
}
}