这是我的代码:
public class ApplicationContext : DbContext
{
private const string databaseName = "Database.db";
public DbSet<Setting> Setting { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
String databasePath = "";
switch (Device.RuntimePlatform)
{
case Device.iOS:
SQLitePCL.Batteries_V2.Init();
databasePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "..", "Library", databaseName); ;
break;
case Device.Android:
databasePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal), databaseName);
break;
case Device.WPF: {
databasePath = Path.Combine(Environment.CurrentDirectory, databaseName);
break;
}
default:
throw new NotImplementedException("Platform not supported");
}
if (!File.Exists(databasePath))
{
File.Create(databasePath);
}
optionsBuilder.UseSqlite($"Filename={databasePath}");
}
}
public class Setting
{
[Key]
public string Key { get; set; }
public string Value { get; set; }
}
在WPF中,一切运行良好。
但是,在Android中,即使我以前使用EnsureCreated
,它也始终报告“没有这样的表”错误。
这是怎么了?我该如何解决?谢谢。
答案 0 :(得分:1)
请确保您安装了正确的nuget软件包:
我用您的代码编写了一个演示,在我这方面效果很好,这是我的代码:
public partial class MainPage : ContentPage
{
public MainPage()
{
InitializeComponent();
ApplicationContext context = new ApplicationContext();
context.Database.EnsureCreated();
Task.Run (async () => {
var newPosts = new Setting() { Key = "123", Value = "test" };
context.Setting.Add(newPosts);
var result = context.Setting.Where(X => X.Key == "123").FirstOrDefault();
Console.WriteLine(result.Value);
} );
}
}
public class ApplicationContext : DbContext
{
private const string databaseName = "Database.db";
public DbSet<Setting> Setting { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
String databasePath = "";
switch (Device.RuntimePlatform)
{
case Device.iOS:
SQLitePCL.Batteries_V2.Init();
databasePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "..", "Library", databaseName); ;
break;
case Device.Android:
databasePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal), databaseName);
break;
case Device.WPF:
{
databasePath = Path.Combine(Environment.CurrentDirectory, databaseName);
break;
}
default:
throw new NotImplementedException("Platform not supported");
}
if (!File.Exists(databasePath))
{
File.Create(databasePath);
}
optionsBuilder.UseSqlite($"Filename={databasePath}");
}
}
public class Setting
{
[Key]
public string Key { get; set; }
public string Value { get; set; }
}
我上传了测试项目here,随时可以问我任何问题。