Domanda

What is the proper way in PetaPoco to hydrate a POCO property that is a collection? I'd like to do something like this, but not sure how.

return db.Fetch<ColorCategory, List<SubColor>, ColorCategory>((c, s) => { c.SubColors = *?*; return c; }, "SELECT [ColorCategory].[ColorCategoryID] " +
            ",[ColorCategory].[DisplayOrder] " +
            ",[ColorCategory].[Name] " +
            ",[ColorCategory].[ModifiedDate] " +
            ",[ColorCategory].[ModifiedUser] " +
            ",[SubColor].[SubColorID] " +
            ",[SubColor].[Name] " +
            "FROM [ColorCategory] " +
            "INNER JOIN [ColorCategorySubColor] ON [ColorCategory].[ColorCategoryID] = [ColorCategorySubColor].[ColorCategoryID] " +
            "INNER JOIN [SubColor] ON [ColorCategorySubColor].[SubColorID] = [SubColor].[SubColorID]");

Where the ColorCategory class has a List property, SubColors.

È stato utile?

Soluzione

You can join the SubColors in the sql query, so you get back a duplicate ColorCategory record for every SubColor as explained here :

http://www.toptensoftware.com/Articles/115/PetaPoco-Mapping-One-to-Many-and-Many-to-One-Relationships

The offcial method (at the moment) is to create a relator class containing some state (about the current record) and a method which PetaPoco will invoke for every row in the resultset. The relator tells PetaPoco when to stop adding SubColors to the ColorCategory and move onto the next parent poco.

However, Schotime has added some brilliant functions that automate this.

This is demonstrated in my test app at GitHub. It's quite simple to program but be aware that the order of the SELECT columns is crucial as PetaPoco relies on the flow being the same as in the Fetch<T1, T2...> poco list.

The alternative is an N+1 approach where you load the SubColors on demand.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top