Search code examples
.netdbextensions

Maxtoroq / DBExtensions How to map child list?


Using Maxtoroq's DBExtensions how can we map an object having list of elements as child property 
using just one sql builder?

My sample DB structure 

Employee
   EmployeeId
   FirstName
   LastName

Department
 DeptId
 DeptName

EmployeeDepartment
  EmployeeId
  DeptId


My POCO 

class Department{

 public int DeptId {get;set;}

 public string DeptName {get;set;}
}

class Employee {

public void Employee(){
  Depts = new List<Department>();
}

  public int EmployeeId {get;set;}

  public string FirstName {get;set;}

  public string LastName {get;set;}

  public List<Department> Depts {get;set;}
}

Now I want to create instance of User including all departments he is associated to using SqlBuilder by running query against db in one go (Not multiple calls to db).

How can I do that?


Solution

  • AFAIK, there are no ORMs that can load an entity including one-to-many association in a single database call.

    You can do this in DbExtensions, but instead of SqlBuilder you use Database/SqlTable:

    class MyDatabase : Database {
    
       public SqlTable<Employee> Employees {
          get { return Table<Employee>(); }
       }
    
       public MyDatabase()
          : base("name=MyDatabase") { }
    }
    
    var db = new MyDatabase();
    
    Employee emp = db.Employees
       .Include("Depts")
       .Find(1);