2

我正在使用 Xamarin.Forms 构建一个新项目,并且我想使用 SQLite 来存储用户数据。我正在使用.Net 标准项目。我在所有 4 个项目(共享代码、机器人、ios 和 uwp)中安装了 Frank A. Krueger 的 sqlite-net-pcl NuGet 包。正如文档告诉您的那样,我在所有项目中创建了 IFileHelper 接口和实现该接口的类。当我第一次启动应用程序时,我想在数据库中插入一些默认值,但我得到了一个异常。我一直在调试,当在 App.xaml.cs 文档上创建数据库时,它只返回 null,所以我没有得到任何数据库。

我一遍又一遍地检查了所有代码,一切都很好,所以我只是想知道 sqlite-net-pcl 是否与 .NET 标准项目兼容?这个问题有什么解决办法吗?

这是 App.xaml.cs 上的代码

static AppDatabase database;

    public App ()
    {
        InitializeComponent();

        MainPage = new MainPage();
    }

    public static AppDatabase Database
    {
        get
        {
            if (database == null)
            {
                database = new AppDatabase(DependencyService.Get<IFileHelper>().GetLocalFilePath("AppDatabase.db3"));
                System.Threading.Thread.Sleep(500);
            }
            return database;
        }
    }

我当我返回数据库时,它只返回 null,所以当我在 AppDatabase 类上创建表时,我得到了异常System.AggregateException: One or more errors occurred.

readonly SQLiteAsyncConnection Database;

        public AppDatabase(string dbPath)
        {
            Database = new SQLiteAsyncConnection(dbPath);
            Database.CreateTableAsync<Stats>().Wait();
        }

我理解这个例外,因为数据库是空的,我不能聚合任何表或任何东西,因为数据库不存在,但为什么它不创建数据库?

这是共享代码的接口

namespace FitApp
{
    public interface IFileHelper
    {
        string GetLocalFilePath(string fileName);
    }
}

以及在 droid 项目上实现接口的类:

[assembly: Dependency(typeof(FitApp.Droid.FileHelper))]
namespace FitApp.Droid
{
    public class FileHelper : IFileHelper
    {
        public string GetLocalFilePath(string fileName)
        {
            string path = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
            return System.IO.Path.Combine(path, fileName);
        }
    }
}

谢谢

4

1 回答 1

1

我发现这个页面真的有助于开始使用 SQLite 和 Xamarin。Xamarin - 使用 SQLite 在 Xamarin.Forms 中处理本地数据库

注意这个页面没有使用async数据库。

我的实施有效。初始化;

public SQLiteAsyncConnection AsyncDb { get; private set; }

    public App ()
    {
        InitializeComponent();
        AsyncDb = DependencyService.Get<IDatabaseConnection>().AsyncDbConnection();
}

界面;

public interface IDatabaseConnection
{
    SQLite.SQLiteAsyncConnection AsyncDbConnection();
}

机器人实现;

public class DatabaseConnection_Droid : IDatabaseConnection
{
    public SQLiteAsyncConnection AsyncDbConnection()
    {
        var dbName = "DiceyData.db3";
        var path = Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal), dbName);
        return new SQLiteAsyncConnection(path);
    }

}

然后您可以对 appwide 属性进行操作,例如; await ((App)Application.Current).AsyncDb.CreateTableAysnc<YourTypeHere>();

于 2018-06-04T00:13:55.793 回答