Kevin Hecker
Kevin Hecker

Reputation: 33

Entity Framework (Loading Nested Entities)

These are my entities...

Public Class Account
    Public Property AccountId As Integer 
    Public Property AccountDescription As String 
    Public Property Transactions As List(Of Transaction) 
End Class

Public Class Transaction 
    Public Property TransactionId As Integer 
    Public Property AccountId As Integer 
    Public Property TransferAccountId As Integer
    Public Property TransactionDescription As String 
End Class 

I now know I can do this. db.Account.Include("Transactions").SingleOrDefault(Function(a) a.AccountId = myAccountId)

However this only includes the transactions that have AccountId = myAccountId obviously. But in my case i want all transactions, including those that are involved in a transfer. so where AccountId = AccountId or TransferAccountId = myAccountId. How can i load an account and its list of transactions and transfertransactions in one call?

Upvotes: 1

Views: 387

Answers (1)

Ladislav Mrnka
Ladislav Mrnka

Reputation: 364259

With your model you cannot do that directly because you have only single Transaction property on Account class. This property will point either to accounts with AccountId == Id or TransferAccountId == Id but never to both. If you want to easily load both types you need two navigation properties on your Account type - one for related transaction and one for transfer transaction, after that you will just use Include for both properties:

db.Account.Include("Transactions")
          .Inclue("TransferTransactions")
          .SingleOrDefault(Function(a) a.AccountId = myAccountId)

If you don't want to add second navigation property you can do it in reverse direction. Query transactions and eager load account. As a last case you can query account and transactions separately.

Upvotes: 1

Related Questions