моя реализация < /h3>
[*] Контекст базы данных: < /strong> < /p>
public class DatabaseContext
{
private readonly IConfiguration _configuration;
public DatabaseContext(IConfiguration configuration)
{
_configuration = configuration;
}
public IDbConnection CreateConnection()
{
return new NpgsqlConnection(_configuration.GetConnectionString("DefaultConnection"));
}
}
[*] generic Repository: [/b]
Код: Выделить всё
public class Repository : IRepository where T : class
{
private readonly DatabaseContext _context;
public Repository(DatabaseContext context)
{
_context = context;
}
public async Task GetAllAsync()
{
using (var connection = _context.CreateConnection())
{
var tableName = typeof(T).Name;
var query = $"SELECT * FROM {tableName}";
return await connection.QueryAsync(query);
}
}
// Other CRUD methods...
}
Код: Выделить всё
[Route("api/[controller]")]
[ApiController]
public class GenericController : ControllerBase where T : class
{
private readonly IRepository _repository;
public GenericController(IRepository repository)
{
_repository = repository;
}
[HttpGet]
public async Task GetAll()
{
return Ok(await _repository.GetAllAsync());
}
// Other CRUD endpoints...
}
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public decimal Price { get; set; }
}
[Route("api/[controller]")]
[ApiController]
public class ProductsController : GenericController
{
public ProductsController(IRepository repository) : base(repository)
{
}
}
< /code>
< /li>
< /ol>
проблема и вопрос < /h3>
Имя таблицы. Однако это предполагает, что имя таблицы точно соответствует имени класса. Что, если имя таблицы отличается? Как я могу справиться с этим динамически? /> Любые предложения или улучшения будут высоко оценены! < /p>
Подробнее здесь: https://stackoverflow.com/questions/795 ... postgresql