简体   繁体   English

使用NPoco 3的嵌套对象映射

[英]Nested object mapping with NPoco 3

I'm trying to get a nested mapping running but the nested object is null. 我正在尝试运行嵌套映射,但嵌套对象为null。 Which means in my case result[0].Location is null. 在我的情况下,这意味着result[0].Location为null。 I'm using NPoco 3.3.0-beta3 together with Postgres. 我正在将NPoco 3.3.0-beta3与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: 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属性中删除属性[ResultColumn] Location property is not a column in the database and does not therefore require the attribute. Location属性不是数据库中的列,因此不需要该属性。

Even if the property was a column in the database, you would require to note the following from NPoco wiki 即使该属性是数据库中的一列,您也需要注意NPoco Wiki中的以下内容

Note: These columns will need to be explicitly specified in the SQL. 注意:这些列将需要在SQL中明确指定。 It will not be included in the auto generated SQL. 它不会包含在自动生成的SQL中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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