I am a C# Desktop developer, And I went to android apps using Xamarin, I used to use…
- User
I am a C# Desktop developer, And I went to android apps using Xamarin, I used to use System.Data.SQLite.Core in my Desktop apps for SQLite.
help me make the following code compatible with sqlite-net-pcl:
private readonly SQLiteConnection _connection;
public SqLiteDatabase(string databaseName) { _connection = new SQLiteConnection($"Data Source={databaseName}.db"); _connection.Open(); InitializeDatabase(); } private void InitializeDatabase() { const string createUsersTableSql = @" CREATE TABLE IF NOT EXISTS Users ( Id TEXT PRIMARY KEY ); ";
const string createCardsTableSql = @" CREATE TABLE IF NOT EXISTS Cards ( Id TEXT PRIMARY KEY, Units REAL, OwnerId INTEGER, Timestamp INTEGER, Remaining INTEGER ); "; const string createUserCardsTableSql = @" CREATE TABLE IF NOT EXISTS UserCards ( UserId TEXT, CardId TEXT, Timestamp INTEGER, PRIMARY KEY(UserId, CardId), FOREIGN KEY(UserId) REFERENCES Users(Id), FOREIGN KEY(CardId) REFERENCES Cards(Id) ); "; ExecuteNonQuery(createUsersTableSql); ExecuteNonQuery(createCardsTableSql); ExecuteNonQuery(createUserCardsTableSql);}
public async Task GetOrAddUserAsync(string userId) { var user = await GetUserAsync(userId); if (user != null) return user;
user = new User(userId); await AddOrUpdateUserAsync(user); return user;} public async Task<User?> GetUserAsync(string userId) { var command = _connection.CreateCommand(); command.CommandText = @" SELECT Id FROM Users WHERE Id = @UserId; "; command.Parameters.AddWithValue("@UserId", userId);
await using var reader = await command.ExecuteReaderAsync(); if (!await reader.ReadAsync()) return null; var id = reader.GetString(0); var cards = GetUserCards(id); return new User(id, cards);} public async Task AddOrUpdateUserAsync(User user) { await using var transaction = _connection.BeginTransaction();
try { var command = _connection.CreateCommand(); command.Transaction = transaction; command.CommandText = @" INSERT OR REPLACE INTO Users (Id) VALUES (@Id); "; command.Parameters.AddWithValue("@Id", user.Id); await command.ExecuteNonQueryAsync(); foreach (var (key, userCard) in user.Cards) { await AddCardIfNotExistAsync(userCard.Card); await AssignCardToUserAsync(user.Id, key, userCard.Timestamp); } transaction.Commit(); } catch (Exception) { transaction.Rollback(); throw; }}
private IEnumerable GetUserCards(string userId) { var command = _connection.CreateCommand(); command.CommandText = @" SELECT Cards.Id, Units, OwnerId, Cards.Timestamp, Remaining, UserCards.Timestamp FROM Cards JOIN UserCards ON Cards.Id = UserCards.CardId WHERE UserCards.UserId = @UserId; "; command.Parameters.AddWithValue("@UserId", userId);
- Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.