mirror of
https://github.com/tribufu/tribufu-dotnet
synced 2026-06-01 09:42:35 +00:00
Update ef core utils
This commit is contained in:
parent
9678659892
commit
02642f9dfa
5 changed files with 30 additions and 164 deletions
|
|
@ -1,105 +0,0 @@
|
|||
// Copyright (c) Tribufu. All Rights Reserved.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using System;
|
||||
|
||||
namespace Tribufu.EntityFrameworkCore
|
||||
{
|
||||
public class DatabaseConfiguration
|
||||
{
|
||||
public DatabaseDriver Driver { get; set; }
|
||||
|
||||
public string? Version { get; set; }
|
||||
|
||||
public string? Host { get; set; }
|
||||
|
||||
public string? Port { get; set; }
|
||||
|
||||
public string? User { get; set; }
|
||||
|
||||
public string? Password { get; set; }
|
||||
|
||||
public string? Schema { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Loads the <see cref="DatabaseConfiguration"/> from the "database" section or from root-level keys prefixed with "database_".
|
||||
/// </summary>
|
||||
/// <param name="configuration">The configuration source.</param>
|
||||
/// <returns>The populated <see cref="DatabaseConfiguration"/> instance.</returns>
|
||||
public static DatabaseConfiguration Load(IConfiguration configuration)
|
||||
{
|
||||
var section = configuration.GetSection("database");
|
||||
var useRootFallback = !section.Exists();
|
||||
|
||||
string? GetConfig(string key) => useRootFallback ? configuration[$"database_{key}"] : section[key];
|
||||
|
||||
var driverString = GetConfig("driver") ?? throw new Exception("Missing database driver");
|
||||
if (!Enum.TryParse<DatabaseDriver>(driverString, true, out var driver))
|
||||
{
|
||||
throw new Exception($"Unsupported database driver: {driverString}");
|
||||
}
|
||||
|
||||
return new DatabaseConfiguration
|
||||
{
|
||||
Driver = driver,
|
||||
Version = GetConfig("version"),
|
||||
Host = GetConfig("host"),
|
||||
Port = GetConfig("port"),
|
||||
User = GetConfig("user"),
|
||||
Password = GetConfig("password"),
|
||||
Schema = GetConfig("schema")
|
||||
};
|
||||
}
|
||||
|
||||
/*
|
||||
services.AddDbContext<DbContext>(options =>
|
||||
{
|
||||
switch (dbConfig.Driver)
|
||||
{
|
||||
case DatabaseDriver.MySql:
|
||||
var mysqlConnection = $"Server={dbConfig.Host};Port={dbConfig.Port};Uid={dbConfig.User};Pwd={dbConfig.Password};Database={dbConfig.Schema};ConvertZeroDateTime=True;";
|
||||
options.UseMySql(mysqlConnection, ServerVersion.Parse(dbConfig.Version ?? "8.0"), mySqlOptions => { });
|
||||
break;
|
||||
case DatabaseDriver.Postgres:
|
||||
var pgsqlConnection = $"Host={dbConfig.Host};Port={dbConfig.Port};Database={dbConfig.Schema};Username={dbConfig.User};Password={dbConfig.Password};";
|
||||
options.UseNpgsql(pgsqlConnection, npgsqlOptions => { });
|
||||
break;
|
||||
case DatabaseDriver.SqlServer:
|
||||
var sqlServerConnection = $"Server={dbConfig.Host},{dbConfig.Port};Database={dbConfig.Schema};User Id={dbConfig.User};Password={dbConfig.Password};Encrypt=True;TrustServerCertificate=True;";
|
||||
options.UseSqlServer(sqlServerConnection, sqlOptions => { });
|
||||
break;
|
||||
case DatabaseDriver.Oracle:
|
||||
var oracleConnection = $"User Id={dbConfig.User};Password={dbConfig.Password};Data Source=(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST={dbConfig.Host})(PORT={dbConfig.Port})))(CONNECT_DATA=(SERVICE_NAME={dbConfig.Schema})));";
|
||||
options.UseOracle(oracleConnection, oracleOptions => { });
|
||||
break;
|
||||
case DatabaseDriver.Firebird:
|
||||
var firebirdConnection = $"User={dbConfig.User};Password={dbConfig.Password};Database={dbConfig.Host}:{dbConfig.Port}/{dbConfig.Schema};Dialect=3;";
|
||||
options.UseFirebird(firebirdConnection, firebirdOptions => { });
|
||||
break;
|
||||
case DatabaseDriver.Sqlite:
|
||||
var savedDirectory = Paths.GetApplicationSavedDirectory();
|
||||
if (!Directory.Exists(savedDirectory)) Directory.CreateDirectory(savedDirectory);
|
||||
var sqliteDatabaseFile = string.IsNullOrEmpty(dbConfig.Schema) ? "default.db" : $"{dbConfig.Schema}.db";
|
||||
var sqliteDatabasePath = Path.Combine(savedDirectory, sqliteDatabaseFile);
|
||||
options.UseSqlite($"Data Source={sqliteDatabasePath}", sqliteOptions => { });
|
||||
break;
|
||||
case DatabaseDriver.MongoDb:
|
||||
var mongoUriBuilder = new MongoUrlBuilder
|
||||
{
|
||||
Server = new MongoServerAddress(dbConfig.Host, int.Parse(dbConfig.Port ?? "27017")),
|
||||
Username = dbConfig.User,
|
||||
Password = dbConfig.Password,
|
||||
DatabaseName = dbConfig.Schema
|
||||
};
|
||||
var mongoClient = new MongoClient(mongoUriBuilder.ToMongoUrl());
|
||||
var mongoDatabase = mongoClient.GetDatabase(dbConfig.Schema ?? "default");
|
||||
options.UseMongoDB(mongoDatabase.Client, mongoDatabase.DatabaseNamespace.DatabaseName);
|
||||
break;
|
||||
default:
|
||||
throw new NotSupportedException($"Unsupported database driver: {dbConfig.Driver}");
|
||||
}
|
||||
});
|
||||
*/
|
||||
}
|
||||
}
|
||||
|
|
@ -1,12 +0,0 @@
|
|||
// Copyright (c) Tribufu. All Rights Reserved.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
namespace Tribufu.EntityFrameworkCore
|
||||
{
|
||||
public static class DatabaseConstants
|
||||
{
|
||||
public const uint DEFAULT_PAGINATION = 20;
|
||||
|
||||
public const uint MAX_PAGINATION = 100;
|
||||
}
|
||||
}
|
||||
|
|
@ -1,22 +0,0 @@
|
|||
// Copyright (c) Tribufu. All Rights Reserved.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
namespace Tribufu.EntityFrameworkCore
|
||||
{
|
||||
public enum DatabaseDriver : byte
|
||||
{
|
||||
MySql = 0,
|
||||
|
||||
Postgres = 1,
|
||||
|
||||
SqlServer = 2,
|
||||
|
||||
Oracle = 3,
|
||||
|
||||
Firebird = 4,
|
||||
|
||||
Sqlite = 5,
|
||||
|
||||
MongoDb = 6,
|
||||
}
|
||||
}
|
||||
|
|
@ -4,23 +4,25 @@
|
|||
using System.Collections.Generic;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace Tribufu.EntityFrameworkCore.Repositories
|
||||
namespace Tribufu.EntityFrameworkCore
|
||||
{
|
||||
public interface IRepository<T, K> where T : class
|
||||
{
|
||||
void Seed();
|
||||
|
||||
Task SeedAsync();
|
||||
|
||||
IList<T> GetAll();
|
||||
IList<T> List();
|
||||
|
||||
Task<IList<T>> GetAllAsync();
|
||||
Task<IList<T>> ListAsync();
|
||||
|
||||
IList<T> GetPage(uint page, uint limit);
|
||||
IList<T> List(uint page, uint limit);
|
||||
|
||||
Task<IList<T>> GetPageAsync(uint page, uint limit);
|
||||
Task<IList<T>> ListAsync(uint page, uint limit);
|
||||
|
||||
T? GetOne(K key);
|
||||
T? Find(K key);
|
||||
|
||||
Task<T?> GetOneAsync(K key);
|
||||
Task<T?> FindAsync(K key);
|
||||
|
||||
T? Create(T entity);
|
||||
|
||||
|
|
@ -7,50 +7,54 @@ using System.Collections.Generic;
|
|||
using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace Tribufu.EntityFrameworkCore.Repositories
|
||||
namespace Tribufu.EntityFrameworkCore
|
||||
{
|
||||
public class Repository<C, T, K> : IRepository<T, K> where C : DbContext where T : class
|
||||
{
|
||||
protected readonly C _context;
|
||||
protected readonly C _dbContext;
|
||||
|
||||
protected readonly DbSet<T> _dbSet;
|
||||
|
||||
public Repository(C context)
|
||||
public Repository(C dbContext)
|
||||
{
|
||||
_dbContext = dbContext ?? throw new ArgumentNullException(nameof(dbContext));
|
||||
_dbSet = dbContext.Set<T>();
|
||||
}
|
||||
|
||||
public virtual void Seed()
|
||||
{
|
||||
_context = context ?? throw new ArgumentNullException(nameof(context));
|
||||
_dbSet = context.Set<T>();
|
||||
}
|
||||
|
||||
public virtual async Task SeedAsync()
|
||||
{
|
||||
}
|
||||
|
||||
public virtual IList<T> GetAll()
|
||||
public virtual IList<T> List()
|
||||
{
|
||||
return [.. _dbSet];
|
||||
}
|
||||
|
||||
public virtual async Task<IList<T>> GetAllAsync()
|
||||
public virtual async Task<IList<T>> ListAsync()
|
||||
{
|
||||
return await _dbSet.ToListAsync();
|
||||
}
|
||||
|
||||
public virtual IList<T> GetPage(uint page, uint limit)
|
||||
public virtual IList<T> List(uint page, uint limit)
|
||||
{
|
||||
return _dbSet.Skip((int)((page < 1 ? 0 : page - 1) * limit)).Take((int)limit).ToList();
|
||||
}
|
||||
|
||||
public virtual async Task<IList<T>> GetPageAsync(uint page, uint limit)
|
||||
public virtual async Task<IList<T>> ListAsync(uint page, uint limit)
|
||||
{
|
||||
return await _dbSet.Skip((int)((page < 1 ? 0 : page - 1) * limit)).Take((int)limit).ToListAsync();
|
||||
}
|
||||
|
||||
public virtual T? GetOne(K key)
|
||||
public virtual T? Find(K key)
|
||||
{
|
||||
return _dbSet.Find(key);
|
||||
}
|
||||
|
||||
public virtual async Task<T?> GetOneAsync(K key)
|
||||
public virtual async Task<T?> FindAsync(K key)
|
||||
{
|
||||
return await _dbSet.FindAsync(key);
|
||||
}
|
||||
|
|
@ -58,29 +62,28 @@ namespace Tribufu.EntityFrameworkCore.Repositories
|
|||
public virtual T? Create(T entity)
|
||||
{
|
||||
_dbSet.Add(entity);
|
||||
|
||||
var result = _context.SaveChanges();
|
||||
var result = _dbContext.SaveChanges();
|
||||
return result > 0 ? entity : null;
|
||||
}
|
||||
|
||||
public virtual async Task<T?> CreateAsync(T entity)
|
||||
{
|
||||
await _dbSet.AddAsync(entity);
|
||||
var result = await _context.SaveChangesAsync();
|
||||
var result = await _dbContext.SaveChangesAsync();
|
||||
return result > 0 ? entity : null;
|
||||
}
|
||||
|
||||
public virtual T? Update(T entity)
|
||||
{
|
||||
_dbSet.Update(entity);
|
||||
var result = _context.SaveChanges();
|
||||
var result = _dbContext.SaveChanges();
|
||||
return result > 0 ? entity : null;
|
||||
}
|
||||
|
||||
public virtual async Task<T?> UpdateAsync(T entity)
|
||||
{
|
||||
_dbSet.Update(entity);
|
||||
var result = await _context.SaveChangesAsync();
|
||||
var result = await _dbContext.SaveChangesAsync();
|
||||
return result > 0 ? entity : null;
|
||||
}
|
||||
|
||||
|
|
@ -105,13 +108,13 @@ namespace Tribufu.EntityFrameworkCore.Repositories
|
|||
public virtual void Delete(T entity)
|
||||
{
|
||||
_dbSet.Remove(entity);
|
||||
_context.SaveChanges();
|
||||
_dbContext.SaveChanges();
|
||||
}
|
||||
|
||||
public virtual async Task DeleteAsync(T entity)
|
||||
{
|
||||
_dbSet.Remove(entity);
|
||||
await _context.SaveChangesAsync();
|
||||
await _dbContext.SaveChangesAsync();
|
||||
}
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue