Search code examples
sqlitexamarin.formsvisual-studio-mac

Xamarin Form Create Table Problem in SqLite based complex class


I develop cross platform mobile app on Xamarin Forms. I try to create tables in sqlite. My class name is 'News' and News class containts 'Country' class.

Create table code and class is like below.

    [Serializable]
    [DataContract]
    public class News
    {
        [PrimaryKey]
        [DataMember]
        public int Id { get; set; }
        [DataMember]
        public Guid ActivityId { get; set; }
        [DataMember]
        public int Type { get; set; }
        [DataMember]
        public string Title { get; set; }
        [DataMember]
        public CountryBase Country { get; set; }
    } 

and code is something like

var db = new SQLiteConnection (dbPath);
db.CreateTable<News> ();

This isn't working. When i remove the country class it works. I try to create country table separately but still i couldn't create News table. How can i fix the problem?


Solution

  • The SQLite doesn't allow relationships, and public CountryBase Country { get; set; } is interpreted as one.

    So you need:

    either to serialize your Country as a string before inserting, and you will have this:

    [DataMember]
    public string SerializedCountry { get; set; }
    
    [Ignore]
    public CountryBase Country { get; set; }
    

    And you need to handle serialization with Json.net manually of the Country.

    Or create another Country table, and specify its id in your entity definition:

    [Serializable]
    [DataContract]
    public class News
    {
        [PrimaryKey]
        [DataMember]
        public int Id { get; set; }
        [DataMember]
        public Guid ActivityId { get; set; }
        [DataMember]
        public int Type { get; set; }
        [DataMember]
        public string Title { get; set; }
        [DataMember]
        public int CountryId { get; set; }
    } 
    
    
    [Serializable]
    [DataContract]
    public class Country
    {
        [PrimaryKey]
        [DataMember]
        public int Id { get; set; }
        [DataMember]
        public string Name { get; set; }
        ...
    }