【问题标题】:How can save in the same table a nested object using NPoco?如何使用 NPoco 在同一个表中保存嵌套对象?
【发布时间】:2014-10-03 16:40:47
【问题描述】:

我有这样的课:

public class AuthEntity 
{
  public int Id { get; set; }

  public AuthResource Resource { get; set; }

  public int ActionId { get; set; }
}

AuthResource 在哪里:

public class AuthResource 
{
  public long ResourceId { get; private set; }

  public int ResourceType { get; private set; }
}

存储数据的表有以下字段:

  • 身份证
  • 资源ID
  • 资源类型
  • ActionId

我可以很好地阅读 AuthEntity(包括 Resource 属性),但我不知道如何插入 AuthEntity 记录。 NPoco 说没有 Resource 字段。如何将嵌套对象字段映射到表字段?

谢谢

【问题讨论】:

    标签: c# npoco


    【解决方案1】:

    NPoco 文档说您可以使用 Mapping To Nested Objects 来做到这一点。

    db.Fetch<AuthEntity, AuthResource>("select query to db")
    

    您还必须将 AuthResource 更改为

    public class AuthResource
    {
         public long ResourceId { get; set; }
         public int ResourceType { get; set; }
    }
    

    【讨论】:

    • 读取操作不是问题,它运行良好。我要做的是在数据库中插入 AuthEntity 对象,并自动将 AuthResource 属性映射到表中的属性。
    【解决方案2】:

    您的表结构表明 ResourceId 和 ResourceType 是 AuthEntity 的成员,而不是单独的类。如果您想将 AuthResource 作为一个单独的类,您可以让 AuthEntity 从 AuthResource 继承,例如

    public class AuthResource
    {
         public long ResourceId { get; private set; }
         public int ResourceType { get; private set; }
    }
    
    public class AuthEntity : AuthResource
    {
        public int Id { get; set; }   
        public int ActionId { get; set; }
    }
    

    这样,AuthEntity 将包含您希望它拥有的 ResourceId 和 ResourceType 值,并且 AuthResource 可以重新用于实现相同结构的其他类,在我看来,这就是您正在寻找的.

    【讨论】:

    • 好吧,我可以这样做,但是 AuthResource 必须聚合到 AuthEntity 而不是它的父级。
    猜你喜欢
    • 2016-08-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-29
    • 1970-01-01
    • 2019-10-13
    • 2017-06-26
    • 2017-02-25
    相关资源
    最近更新 更多