简体   繁体   中英

Nested object mapping with NPoco 3

I'm trying to get a nested mapping running but the nested object is null. Which means in my case result[0].Location is null. I'm using NPoco 3.3.0-beta3 together with Postgres.

Here the code snippet:

var db = new Database(new NpgsqlConnection(configurations["ConnectionStrings:Database"]));

var sql = Sql.Builder
    .Append("SELECT r.*, l.* FROM race r")
    .Append("INNER JOIN location l ON r.location_id = l.id");

using (db.Connection)
{
    db.Connection.Open();
    var result = Db.Fetch<RaceEntity>(sql);
    // result[0].Location == null
}

RaceEntity:

[TableName("race")]
[PrimaryKey("id", AutoIncrement = true)]
public class RaceEntity
{
    [Column("id")]
    public int Id { get; set; }

    [Column("name")]
    public string Name { get; set; }

    [Column("location_id")]
    public int LocationId { get; set; }

    [Column("date")]
    public DateTime Date { get; set; }

    [ResultColumn]
    public LocationEntity Location { get; set; }
}

LocationEntity

[TableName("location")]
[PrimaryKey("id", AutoIncrement = true)]
public class LocationEntity
{
    [Column("id")]
    public int Id { get; set; }

    [Column("name")]
    public string Name { get; set; }

    [Column("province")]
    public string Province { get; set; }

    [Column("postal")]
    public string Postal { get; set; }

    [Column("country")]
    public string Country { get; set; }

    [Column("iso_code")]
    public string IsoCode { get; set; }
}

Race Table

CREATE TABLE "race" (
    "id" SERIAL PRIMARY KEY,
    "name" VARCHAR(100) NOT NULL,   
    "location_id" INTEGER REFERENCES "location" (id),
    "date" date NOT NULL
);

Location Table

CREATE TABLE "location" (
    "id" SERIAL PRIMARY KEY,
    "name" VARCHAR(100) NOT NULL,
    "province" VARCHAR(100) NULL DEFAULT NULL,
    "postal" VARCHAR(30) NULL DEFAULT NULL,
    "country" VARCHAR(70) NOT NULL,
    "iso_code" VARCHAR(10) NULL DEFAULT NULL
);

Remove attribute [ResultColumn] from Location property. Location property is not a column in the database and does not therefore require the attribute.

Even if the property was a column in the database, you would require to note the following from NPoco wiki

Note: These columns will need to be explicitly specified in the SQL. It will not be included in the auto generated SQL.

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