首页 > 解决方案 > nPoco - 使用嵌套数据获取单个对象

问题描述

我有两个 Dto:

[TableName("Address")]
    public class AddressDto
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string City { get; set; }
        public string Street { get; set; }
        public string Building { get; set; }
        public string Appartment { get; set; }
        public string ZipCode { get; set; }
        public string Floor { get; set; }
        public DateTime CreatedDate { get; set; }
    }

[TableName("DistributionPoint")]
    public class DistributionPointDto
    {
        [Column("Id")]
        public int Id { get; set; }

        public string Name { get; set; }

        [Reference(ReferenceType.Foreign, ColumnName = "AddressId", ReferenceMemberName = "Id")]
        public AddressDto Address { get; set; }
    }

如何使用 nPoco 获得带有嵌套 AddressDto 的 DistributionPointDto?我有一个用于 CRUD 的通用存储库,方法如下:

 public T FindById<T>(int id)
        {
           return _db.SingleById<T>(id);
        }

但是,当我尝试获取 DistributionPointDto 时,AddressDto 是null

标签: c#ormrepository-patternnpoco

解决方案


好奇你的代码是否可以工作,但我发现你需要使用 Query 而不是 SingleById 来包含引用的属性,然后你可以使用 Include 语句/子句,但是我不认为泛型适用于此,你必须明确提及引用的属性名称,即为您的 AddressDTO。

_db.Query<DistributionPointDTO>()
  .Include(x => x.AddressDTO)
  .Where(x => x.Id == id).First();
        

推荐阅读