简体   繁体   English

如何使用NPoco在同一个表中保存嵌套对象?

[英]How can save in the same table a nested object using NPoco?

I have a class like this: 我有一个这样的课:

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

  public AuthResource Resource { get; set; }

  public int ActionId { get; set; }
}

where AuthResource is: AuthResource在哪里:

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

  public int ResourceType { get; private set; }
}

The table where the data is stored has the following fields: 存储数据的表具有以下字段:

  • Id ID
  • ResourceId RESOURCEID
  • ResourceType 的ResourceType
  • ActionId ActionId

I can read the AuthEntity well (including Resource property) but I don't know how do I insert AuthEntity records. 我可以很好地阅读AuthEntity(包括Resource属性),但我不知道如何插入AuthEntity记录。 NPoco says that there is no Resource field. NPoco说没有资源字段。 How can I map the nested object fields to the table fields? 如何将嵌套对象字段映射到表字段?

Thanks 谢谢

The NPoco documentation says you can do this with Mapping To Nested Objects . NPoco文档说您可以使用映射到嵌套对象来执行此操作。

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

Also you have to change your AuthResource to 您还必须将AuthResource更改为

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

Your table structure indicates that ResourceId and ResourceType are members of AuthEntity, and are not a separate class. 您的表结构表明ResourceId和ResourceType是AuthEntity的成员,并且不是单独的类。 If you wanted to have AuthResource as a separate class you could make AuthEntity inherit from AuthResource eg 如果你想将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; }
}

in this way AuthEntity would contain the ResourceId and ResourceType values that you want it to have and AuthResource can be re-used for other classes that implement the same structure, which, it seems to me, is what you're looking for. 通过这种方式,AuthEntity将包含您希望它拥有的ResourceId和ResourceType值,并且AuthResource可以重用于实现相同结构的其他类,在我看来,这是您正在寻找的。

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

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