【问题标题】:nPoco - Get single object with nested datanPoco - 使用嵌套数据获取单个对象
【发布时间】:2019-03-11 14:53:32
【问题描述】:

我有两个 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

【问题讨论】:

  • 您的实体数据映射是什么样的?两个表(类)之间的链接可能丢失或错误。
  • 我使用 Dto 中的属性进行映射
  • 首先获取所有 AddressDto 以确保问题不是 ID。如果进行了任何更改,则可能需要刷新映射。一个常见问题是连接字符串映射到旧版本的数据库。所以检查连接字符串。
  • public IQueryProviderWithIncludes&lt;T&gt; GetAll&lt;T&gt;() { return _db.Query&lt;T&gt;(); } 没问题。当我获得所有 DistributionPointDto 时,我可以包含 AddressDto
  • 那么Id不匹配。 Id 列名称是“Id”还是“AddressId”?数据库中的Id是字符串还是整数?

标签: c# orm repository-pattern npoco


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-10-03
    • 2016-08-26
    • 2019-10-13
    • 1970-01-01
    • 1970-01-01
    • 2018-06-12
    • 2019-08-25
    • 2018-06-24
    相关资源
    最近更新 更多