【问题标题】:SQLite object can't be set in UWP - Xamarin Forms无法在 UWP 中设置 SQLite 对象 - Xamarin Forms
【发布时间】:2018-09-07 00:13:39
【问题描述】:

请考虑以下问题:

我正在尝试在跨 iOS、Android 和 Windows 10 设备的 Xamarin Forms 应用中使用 SQLite 数据库。

我的数据库模型处于可移植级别,并根据文档使用接口来实现特定于平台的 SQLite 连接,我的 iOS 和 Android 实现工作得很好,但我似乎无法让我的 UWP 版本正常工作。似乎每当我尝试对我的 SQLiteConnection database 对象做任何事情时,我都会收到异常 Object reference not set to an instance of an object

请在下面查看我的 PCL 和设备特定代码:

Database.cs(共享)

public class Database
{
    static object locker = new object();
    public static SQLiteConnection database;

    public Database()
    {
        Debug.WriteLine("Attempting to build connection");
        try
        {
            if(database == null)
            {
                Debug.WriteLine("DATABASE IS NULL");
            }

            database = DependencyService.Get<ISQLite>().GetConnection(); // <- Crashes here with: Object reference not set to an instance of an object
            Debug.WriteLine("Get Type: " + database.GetType().ToString());
            Debug.WriteLine("DB Path: " + database.DatabasePath);
        }
        catch (Exception ex)
        {
            Debug.WriteLine(ex.Message);
        }

        database.CreateTable<User>();
    }
}

ISQLite_Windows.cs(特定于设备)

class ISQLite_Windows : ISQLite
{
    public ISQLite_Windows()
    {
    }

    public SQLiteConnection GetConnection()
    {
        Debug.WriteLine("This debug never seems to fire");
        var sqliteFilename = "EventManagementSystem.db3";
        string path = Path.Combine(ApplicationData.Current.LocalFolder.Path, sqliteFilename);
        var conn = new SQLiteConnection(path);
        Debug.WriteLine("Connection made, returning");
        return conn;
    }
}

有用信息

我正在使用 sqlite-net-pcl 版本 1.5.166-beta 的 beta NuGet 包,因为这似乎是 UWP 的建议选择。

我正在使用 5.2.2 版的 NuGet 包Microsoft.NETCore.UniversalWindowsPlatform

应用程序构建和智能感知没有发现任何错误,但在 App.cs 初始化期间它会中断。

我似乎无法在我的机器上找到正在创建的数据库文件,尽管我怀疑这是因为它在它到达那么远之前就损坏了。这个问题似乎更多地与访问共享级别的数据库对象有关,而不是设备特定的实现,尽管我很可能错了。

【问题讨论】:

  • 我相信是数据库 = DependencyService.Get().GetConnection();
  • 好吧,这会引发一个被捕获的异常,但是对数据库的任何其他引用似乎也一样,GetConnection 只是我第一次尝试对数据库做任何事情
  • 您说的完全正确,它没有正确注册。非常感谢!如果您想将此作为答案,我很乐意接受

标签: c# sqlite xamarin.forms uwp xamarin.uwp


【解决方案1】:

docs 状态:

注册——每个实现类都必须注册 DependencyService 通过元数据属性。注册启用 DependencyService 查找实现类并将其提供给 界面在运行时的位置。

问题的最可能原因是ISQLite 没有已注册的实现类。

【讨论】:

    猜你喜欢
    • 2017-11-24
    • 2016-12-02
    • 2018-01-18
    • 2018-06-02
    • 2019-01-14
    • 2018-06-30
    • 2018-11-13
    • 1970-01-01
    • 2018-11-06
    相关资源
    最近更新 更多