实体框架(加载嵌套实体)

时间:2012-04-24 14:14:55

标签: asp.net asp.net-mvc entity-framework entity-framework-4

这些是我的实体......

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 

我现在知道我可以做到这一点。 db.Account.Include(“Transactions”)。SingleOrDefault(Function(a)a.AccountId = myAccountId)

但是,这仅包括明显具有AccountId = myAccountId的交易。但在我的情况下,我想要所有交易,包括转移中涉及的交易。所以在AccountId = AccountId或TransferAccountId = myAccountId的地方。如何在一次通话中加载帐户及其交易清单和转账交易?

1 个答案:

答案 0 :(得分:1)

使用您的模型,您无法直接执行此操作,因为Transaction类上只有一个Account属性。此属性将指向包含AccountId == IdTransferAccountId == Id的帐户,但从不指向两者。如果您想轻松加载这两种类型,您需要在您的帐户类型上使用两个导航属性 - 一个用于相关交易,一个用于转移交易,之后您将只使用两个属性的包含:

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

如果您不想添加第二个导航属性,可以反向执行。查询交易和预先加载的帐户。作为最后一种情况,您可以单独查询帐户和交易。