Skip to content

One to Many Query Helpers

jaime-lynn edited this page Mar 22, 2018 · 12 revisions

These helpers allow you to map a query that has a one-to-many relationship to nested list objects. Given the following classes:

    public class UserDto
    {
        public int UserId { get; set; }
        public string Name { get; set; }
        public List<CarDto> Cars { get; set; }
    }

    public class CarDto
    {
        public string Make { get; set; }
        public string Color { get; set; }
    }

and the following query:

IDatabase db = new Database("connStringName");

//v2
var users = db.FetchOneToMany<UserDto, CarDto>(x => x.UserId, 
    "select u.*, c.* from Users u inner join Cars c on u.UserId = c.UserId order by u.UserId");

//v3
var users = db.FetchOneToMany<UserDto>(x => x.Cars, 
    "select u.*, c.* from Users u inner join Cars c on u.UserId = c.UserId order by u.UserId");

This will give you a list of UserDto objects and for each of these the list of CarDto's will also be populated.

Note:

  1. The first parameter to this method is a lambda expression which identifies the unique property of the first object.
  2. The order of the columns is extremely important. It must align with the order of the generic parameters defined. In this example the query specifies u.* then c* which maps to <UserDto, CarDto>.
  3. If you are mapping to objects that are also used for inserting data then you will need to make sure you ignore the List<> property using the [ResultColumn] or [ComputedColumn] attribute.
  4. If you are using an outer join for your query and you are expecting that some of the many's will not be populated, make sure to use the second lambda in the FetchOneToMany call. This should return the property of the primary of the many object. In the above example this might be x => x.CarId.
  5. FetchOneToMany cannot be used to fetch nested one-to-many relationships, or multiple one-to-many relationships. For example, if UserDto also had a list of BoatsDto, only the CarDto list or the BoatsDto list can be loaded and mapped with one query.