开发者

Linq getting child items

When I do a lunq query on an EF model, does it not get child entities we well? I have a Transaction table, which has link to a Payee, and a transaction type entity. Also, each transaction has a list of transaction lines...

But the code bellow - all the child objects seen to be NULL, yet the data in the actual entity (Date) seems OK. But in the line: t.account.account_id; .... 'account' is NULL.

 public static List<AccountTransactionDto> GetTransaction()
    {
        var trans = (from t in Db.account_transaction
                     select t).ToList();
        List<AccountTransactionDto> al = new List<AccountTransactionDto>();

        foreach(var t in trans)
        {
            AccountTransactionDto a = new AccountTransactionDto();
            a.AccountId = t.account.account_id;
            a.AccountTransactionId  = t.account_transaction_id;
            a.PayeeId = t.payee.payee_id;
            a.TransactionDate = t.transaction_date;
            a.TransactionTypeId = t.z_transaction_type.transaction_type_id;

            foreach(var tl in t.account_transaction_line)
       开发者_如何学Python     {
                AccountTransactionLineDto l = new AccountTransactionLineDto();
                l.AccountTransactionLineId = tl.account_transaction_line_id;
                l.Amount = tl.amount;
                l.BudgetId = tl.budget.budget_id;
                l.CostCenterId = tl.cost_centre.cost_centre_id;
                l.SubCategoryId = tl.sub_category.sub_category_id;
                a.AccountTransactionLine.Add(l);
            }

            al.Add(a);
        }
        return al;
    }


You have two options. You can enable the Lazy Loading via:

Db.ContextOptions.LazyLoadingEnabled = true;

Or if you change the query line to this (exact syntax may not be correct for Include):

var trans = (from t in Db.account_transaction
             select t).Include("account_transaction.account_transaction_line");

Then it should pull back the child records with the parent record in a single result set. But this has performance penalties if there is a great amount of data.


Lazy loading needs to be enabled on your data context.

Db.ContextOptions.LazyLoadingEnabled = true;

or you need to explicitly tell EF to load the association. i.e.

var trans = (from t in Db.account_transaction.Include('account').Include('payee') select t).ToList();

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜