-
Notifications
You must be signed in to change notification settings - Fork 0
Example.DbRepository
IzayoiJiichan edited this page Aug 23, 2024
·
2 revisions
using Izayoi.Data;
using Izayoi.Data.Query;
using Izayoi.Data.Repository;
public class UserRepository : DbRepositoryBase<User, int>
{
public UserRepository(IDbDataMapper dbDataMapper, QueryOption queryOption)
: base(dbDataMapper, queryOption) { }
public UserRepository(IDbCommandAdapter dbCommandAdapter)
: base(dbCommandAdapter) { }
}
using System.Collections.Generic;
using System.Threading.Tasks;
using Izayoi.Data;
using Izayoi.Data.Query;
using Microsoft.Data.SqlClient; // for SQL Server
//using Microsoft.Data.Sqlite; // for SQLite
//using MySqlConnector; // for MySQL
//using Npgsql; // for PostgreSQL
public class Example
{
private readonly string dbConnectionString;
private readonly DbCommandAdapter dbCommandAdapter;
private readonly DbDataMapper dbDataMapper;
private readonly QueryOption queryOption;
private readonly UserRepository userRepository;
public Example()
{
queryOption = new QueryOption(RdbKind.SqlServer);
dbDataMapper = new DbDataMapper();
dbCommandAdapter = new DbCommandAdapter(dbDataMapper, queryOption);
userRepository = new UserRepository(dbCommandAdapter);
}
public async Task Method1(CancellationToken cancellationToken)
{
using SqlConnection dbConnection = new(dbConnectionString);
dbConnection.Open();
List<User> users = await userRepository.FetchAllAsync(dbConnection, cancellationToken);
User? user = await userRepository.FetchAsync(dbConnection, id: 1, cancellationToken);
dbConnection.Close();
}
public async Task Method2(CancellationToken cancellationToken)
{
using SqlConnection dbConnection = new(dbConnectionString);
dbConnection.Open();
var user = new User()
{
Id = 0,
Name = "name1",
Age = 20,
Gender = GenderType.Male,
CreatedAt = DateTime.UtcNow,
UpdatedAt = DateTime.UtcNow,
};
int affectedRowCount;
affectedRowCount = await userRepository.InsertReturnAsync(dbConnection, user, cancellationToken);
user.Age = 21;
user.UpdateAt = DateTime.UtcNow;
affectedRowCount = await userRepository.UpdateAsync(dbConnection, user, cancellationToken);
affectedRowCount = await userRepository.DeleteAsync(dbConnection, user, cancellationToken);
dbConnection.Close();
}
}
- Izayoi.Data
- Izayoi.Data.Query
- Izayoi.Data.Repository
- Izayoi.Data.Validation
Examples