Search code examples
sqlitexamarinxamarin.formsxamarin.iossqlite.net

SQLite.net database with Xamarin.Forms App


I have a problem with an SQLite database in my Xamarin.Forms PCL project. I have followed this example from Microsoft Docs:

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

I've been using my own types to store data and it's worked Ok for simple custom types, but I've recently added List<int> and Attendance type to the custom object (Info).

Now when I try and create the object, i get the following errors:

Don't know about System.Collections.Generic.List`1[System.Int32] Don't know about MyApp.Attendance

Here is the init code:

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

I'm using Xamarin.Forms with Xamarin.iOS.


Solution

  • You can not store them by default like that. However there is sqlite-net-extensions which you can use to accomplish that. You can take a look about sqlite-net-extensions here.

    Using this extension you will be able to do that with TextBlob property, something like this:

    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
      }
    

    More explanation about TextBlob from url.

    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.

    I just saw that there is also similar/same questions about this topic on StackOverflow already, so you can take a look at them also.