Craig
Craig

Reputation: 18684

Linq and their sub queries

I have a method that returns me a number of transactions, based on an accountId.

So, in my data accessor, I do this:

var items = (from c in Context.transactions where c.accountid == accountId select c).ToList();

I then call a method that I have that translates the entity framerwork objects, into my own custom DTO objects, and that then returns an object I pass through my service, logic and to my MVC controller.

The translater gets adjoining data. So, my custom DTO might have a field called 'AccountName string' and 'AccountType string'.

Account name is in a table that is foreign key'd to the Transaction table, and AccountType is then foreign key'd to the Account table.

So, my translater would look something like:

var return = new TransactionDto {
    tranactionId = source.id,
    accountName = source.Account.Description,
    accountType = source.Account.AccountType.description
}

I seem to have a speed issue, and I am wondering if my understanding of Linq is to blame. I thought that the ToList() on the initial data retrieval was the end of the select. It then passes all the data to var items .. but maybe my translater is actually doing a select for the 'Account' table, and then another select for the 'AccountType' table. I mean, does the initial 'from c in Context...' get all the foreign key'd tables?

Upvotes: 0

Views: 70

Answers (1)

MarcinJuraszek
MarcinJuraszek

Reputation: 125620

It's called lazy loading. Use Include to eagerly load necessary navigation properties objects:

var items = Context.transactions
                   .Include("Account")
                   .Include("Account.AccountType")
                   .Where(x => x.accountId == accountId)
                   .ToList();

Upvotes: 3

Related Questions