简体   繁体   中英

Sqlite-net extensions relations always null

I am trying to use the extension in MvvmCross 4. What I am trying to do is simple: I have two tables with a one to many relationship and and want to access this.

I have two classes, BusLine and BusLineGroup . Each BusLine has one Group as foreign key. What I do in code is run a simple LINQ-Query to get all Buslines:

var testQuery = 
    from busLine in this._connection.Table<BusLine>()
    select busLine;

The query itself works, but if I check the fields of the returned objects, the Group is always null !. See below for the class and table definitions.

调试本地人

What am I doing wrong? Why is the group always null ? Thanks for your help.


The classes in code:

    public class BusLine
    {
        [PrimaryKey, AutoIncrement]
        public int Id { get; set; }
        public string Name { get; set; }
        [ForeignKey(typeof(BusLineGroup))]
        public int BusLineGroup { get; set; }
        [ManyToOne]
        public BusLineGroup LineGroup { get; set; }
    }

    public class BusLineGroup
    {
        [PrimaryKey, AutoIncrement]
        public int Id { get; set; }
        public string Name { get; set; }
        public string Color { get; set; }
        public string MainStations { get; set; }
        [OneToMany(CascadeOperations = CascadeOperation.All)]
        public List<BusLine> BusLines { get; set; }

    }

The two tables:

CREATE TABLE "BusLineGroup" (
    `Id`    INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE,
    `Name`  TEXT NOT NULL,
    `Color` TEXT NOT NULL,
    `MainStations`  TEXT NOT NULL
);
CREATE TABLE "BusLine" (
    `Id`    INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE,
    `Name`  TEXT NOT NULL,
    `BusLineGroup`  INTEGER NOT NULL,
    FOREIGN KEY(`BusLineGroup`) REFERENCES `BusLineGroup`(`Id`)
);

Installed Nuget-Packages:

  • MvvmCross.Plugin.SQLitePCL
  • SQLiteNetExtensions

Note: The MvvmCross package automatically includes SQLite.Net-PCL. So both of those two use the same PCL.

You are not using any SQLite-Net Extensions method there, you are using plain sqlite.net methods that know nothing about your relationships. You have to use the WithChildren methods to read and write relationships from database.

For example, your query can be replaced with this line:

var testQuery = this._connection.GetAllWithChildren<BusLine>();

That will also fetch first-level relationships from database.

I'd recommend you to take a look at the SQLite-Net Extensions documentation and the sample project for more examples.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM