SQLite.net 数据库与 Xamarin.Forms 应用程序

SQLite.net database with Xamarin.Forms App

我的 Xamarin.Forms PCL 项目中的 SQLite 数据库有问题。 我遵循了 Microsoft Docs 中的这个示例:

https://docs.microsoft.com/en-us/xamarin/xamarin-forms/app-fundamentals/databases

我一直在使用我自己的类型来存储数据,它对简单的自定义类型工作正常,但我最近向自定义对象 (Info) 添加了 List<int> 和出勤类型。

现在,当我尝试创建对象时,出现以下错误:

不知道 System.Collections.Generic.List`1[System.Int32] 不知道 MyApp.Attendance

初始化代码如下:

readonly SQLiteAsyncConnection database;
database = new SQLiteAsyncConnection(dbPath);
database.CreateTableAsync<UserPrefrences>().Wait();
database.CreateTableAsync<Attendance>().Wait();
database.CreateTableAsync<Info>().Wait();

我正在使用 Xamarin.Forms 和 Xamarin.iOS。

默认情况下您不能存储它们。但是,您可以使用 sqlite-net-extensions 来完成它。你可以看看sqlite-net-extensions here.

使用此扩展程序,您将能够通过 TextBlob 属性 执行此操作,如下所示:

public class Address
{
     public string StreetName { get; set; }
     public string Number { get; set; }
     public string PostalCode { get; set; }
     public string Country { get; set; }
}

public class Person
{
     public string Name { get; set; }

     [TextBlob("PhonesBlobbed")]
     public List<string> PhoneNumbers { get; set; }

     [TextBlob("AddressesBlobbed")]
     public List<Address> Addresses { get; set; }

     public string PhonesBlobbed { get; set; } // serialized phone numbers
     public string AddressesBlobbed { get; set; } // serialized addresses
  }

来自 url 的有关 TextBlob 的更多解释。

Text blobbed properties Text-blobbed properties are serialized into a text property when saved and deserialized when loaded. This allows storing simple objects in the same table in a single column.

Text-blobbed properties have a small overhead of serializing and deserializing the objects and some limitations, but are the best way to store simple objects like List or Dictionary of basic types or simple relationships.

Text-blobbed properties require a declared string property where the serialized object is stored.

我刚看到 Whosebug 上已经有 similar/same 个关于这个主题的问题,所以你也可以看看它们。

  • Can I use a List of String in a class intended for SQLite?