2011年7月14日

[EF4] Loading related objects explicitly

In EF4, we can set LazyLoadingEnabled to true to enable lazy loading feature, which, allows us to access database only when related database object (i.e, detail tables) are explicitly accessed in code.

This creates pros & cons. but if we do not pay much attention to it, it could make too much connections to the database then we expected and leads to database performance issues.

There’re several topic we need to consider to choose if we want lazy loading or eager loading, here’s a good MSDN article to help us to make our decision, also with useful code examples.

The following codes are a note on how to explicitly load related objects with one query.

        protected MASTER_TABLE[] QueryApplyFormDataRelated(Func<MASTER_TABLE, bool> where) {
            using (var db = new DBEntities()) {
                using (TransactionScope scope = new TransactionScope(
                                                                        TransactionScopeOption.Required,
                                                                        new TransactionOptions {
                                                                            IsolationLevel = IsolationLevel.ReadUncommitted,
                                                                            Timeout = TimeSpan.FromSeconds(10)
                                                                        })) {
                    db.ContextOptions.LazyLoadingEnabled = false;
                    var table = db.MASTER_TABLE.Include("EMPLOYEE_DETAIL.SALARY_DATA").Include("VENDOR_DETAIL.PAYMET_DATA").Where(where);
                    return table.ToArray();
                }
            }
        }

沒有留言:

Blog Archive

About Me