Jeff
Jeff

Reputation: 12163

Repository pattern and lazy loading + AutoMapper

I've split my project into (as of this time) 4 layers:

The MVC Controllers use the business logic "services" to talk to the database through whatever lies beneath the business logic layer, and the controller should not need to tell anyone that "I want this Student, and I also want all his Courses" - this implies that lazy loading should be used.

The thing is, if I just "call through" and return the result to whoever calls the controller action, I can't really control what gets loaded unless I explicitly access the properties on the model to trigger the loading of the graph.

I'd like to use AutoMapper to map from my model to a Dto (one for each model, which defines what gets returned).

Say I have a model like this:

public class Student 
{
    public string Name {get;set;}
    public int Age {get;set;}
    public ICollection<Course> Courses {get;set;}
}

And a dto like this:

public class StudentDto
{
    public string Name {get;set;}
    public ICollection<Course> Courses {get;set;}
}

When AutoMapper does the mapping, it doesen't appear to map the Courses, which is my problem.

Should I be eager-loading at the repository layer instead?

Upvotes: 2

Views: 1947

Answers (1)

Jayantha Lal Sirisena
Jayantha Lal Sirisena

Reputation: 21366

As you have in the Student and StudentDto Automapper should map object graph correctly to the dto. This will work only if lazy loading enabled otherwise you may need to use eager loading.

I think the best way to choose what method to use is to test the performance of both method which will depend on several factors like your data model in the db and the delay between the sql server and your application etc.. .
Edit.. How to choose the best method
How to choose the best method You need to consider three things,

  1. How many connections that you are going to make with the database. If you are using lazy loading there will be a database call for all the reference points of a navigation properties if referred navigation property is not in the context.

  2. How much data that you are going to retrieve from databaseIf you choose to load all the data in initial query with differed loading it will be too slow when you have huge amount of data to retrieve.

  3. Complexity of the query . When you are using lazy loading the queries will be simple because all the data is not loaded in the initial query. If you use immediate loading it will make quires will be more complex with query paths

read more here

Upvotes: 2

Related Questions