我正在尝试为纸牌游戏创建一个计数器,并且我正在尝试将“匹配”与数据库中的点一起存储。我已经安装了 nuget 包
sqlite-net-pcl
,但出现错误:
“没有这样的表”,即使我通过 CreateTable 命令创建表。
关于DB的自定义类:
using SQLite;
namespace Tichu_Counter
{
public class DBManager
{
private const string db_name = "tichu_counter_db.db3";
static SQLiteAsyncConnection dbconnection;
public DBManager()
{
}
static async Task Init()
{
if (dbconnection != null)
return;
dbconnection = new SQLiteAsyncConnection(Path.Combine(FileSystem.AppDataDirectory, db_name));
await dbconnection.CreateTableAsync<Match>();
}
public async Task<List<Match>> GetMatches()
{
await Init();
return await dbconnection.Table<Match>().ToListAsync();
}
public async Task AddMatch(Match match)
{
await Init();
await dbconnection.InsertAsync(match);
}
public async Task UpdateMatch(Match match)
{
await Init();
await dbconnection.UpdateAsync(match);
}
public async Task DeleteMatch(Match match)
{
await Init();
await dbconnection.DeleteAsync(match);
}
}
}
这是我使用它的地方
public MainPage()
{
dbManager = new DBManager();
InitializeComponent();
CreateMatch(); //Calling AddMatch()
Load_Matches(); //Calling GetMatches()
selectedindex = 0;
}
这些是属性
namespace Tichu_Counter
{
[Table("matches")]
public class Match
{
[PrimaryKey,AutoIncrement]
[Column("Match_ID")]
public int match_ID { get; set; }
[Column("Name_A")]
public String name_A { get; set; }
[Column("Name_B")]
public String name_B { get; set; }
[Column("Score_A")]
public int score_A { get; set; }
[Column("Score_B")]
public int score_B { get; set; }
[Column("Rounds_A")]
public String rounds_a { get; set; }
[Column("Rounds_B")]
public String rounds_b { get; set; }
[Column("Selected")]
public bool selected { get; set; }
[Column("Date")]
public string date { get; set; }
我已尝试使用同步连接,但仍然存在问题。
该错误表明命令
dbconnection.CreateTableAsync<Match>();
无法创建所需的表。
如何在MAUI上正确使用
Database
,您可以参考以下建议。
安装 SQLite NuGet 包:sqlite-net-pcl 和 SQLitePCLRaw.bundle_green
配置应用程序常量:
public static class Constants
{
public const string DatabaseFilename = "tichu_counter_db.db3";
public const SQLite.SQLiteOpenFlags Flags =
// open the database in read/write mode
SQLite.SQLiteOpenFlags.ReadWrite |
// create the database if it doesn't exist
SQLite.SQLiteOpenFlags.Create |
// enable multi-threaded database access
SQLite.SQLiteOpenFlags.SharedCache;
public static string DatabasePath =>
Path.Combine(FileSystem.AppDataDirectory, DatabaseFilename);
}
public class DBManager
{
SQLiteAsyncConnection Database;
public DBManager()
{
}
async Task Init()
{
if (Database is not null)
return;
Database = new SQLiteAsyncConnection(Constants.DatabasePath, Constants.Flags);
var result = await Database.CreateTableAsync<Match>();
}
更多详情可以参考官方文档:.NET MAUI本地数据库。