Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

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:

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
  • ResourceId
  • ResourceType
  • ActionId

I can read the AuthEntity well (including Resource property) but I don't know how do I insert AuthEntity records. NPoco says that there is no Resource field. How can I map the nested object fields to the table fields?

Thanks

like image 705
dsancho Avatar asked Oct 21 '22 03:10

dsancho


2 Answers

The NPoco documentation says you can do this with Mapping To Nested Objects .

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

Also you have to change your AuthResource to

public class AuthResource
{
     public long ResourceId { get; set; }
     public int ResourceType { get; set; }
}
like image 100
Ajay Peter Avatar answered Oct 22 '22 18:10

Ajay Peter


Your table structure indicates that ResourceId and ResourceType are members of AuthEntity, and are not a separate class. If you wanted to have AuthResource as a separate class you could make AuthEntity inherit from AuthResource e.g.

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.

like image 36
Greg Avatar answered Oct 22 '22 16:10

Greg