4

I'm familiarizing with PetaPoco (it looks great btw), but have one blocker here, and I'm curious if I can do that in PetaPoco.

What I would like to do, is to map one row in the database into a composite object. I think that example will clear things up.

Suppose, we have a table in the database called 'Customers' and row looks somethins like this:

ID | Name     | City     | Street           | 
1  | John Doe | New York | Some Street Name |

and I would like to use model like that:

public class Customer
{
    public int Id { get; set; }
    public string Name { get; set; }
    public Address Address { get; set; }
}

public class Address
{
    public string City{ get; set; }
    public string Street { get; set; }
}

So we have to different objects in c#, but it's only one entity (one Id, one row in the database).

Can I achieve such mapping using PetaPoco ?

Biegal
  • 41
  • 1
  • 2

1 Answers1

2

Yes, you can, it's as simple as:

var customers = db.Fetch<customer, address>(@"
        SELECT * FROM customers
        LEFT JOIN adresses ON customers.customerID = adresses.customerID 
        ORDER BY customers.customerID
        ");

More info on that and other multimappings in http://www.toptensoftware.com/blog/posts/115-PetaPoco-Mapping-One-to-Many-and-Many-to-One-Relationships

David Swindells
  • 641
  • 1
  • 12
  • 28
Eduardo Molteni
  • 38,786
  • 23
  • 141
  • 206
  • 1
    Solution you are presenting is using two tables (standard relation by id). What I would like to achieve in my question is two have only one table in the database for this and two object on C# side (Address in this example don't have id at all). Thx! – Biegal Apr 20 '12 at 12:21