Click here to Skip to main content
15,881,381 members
Articles / Programming Languages / C#

Comparing Transparent Lazy Loading between NHibernate and Entity Framework

Rate me:
Please Sign up or sign in to vote.
5.00/5 (2 votes)
14 Jan 2012CPOL7 min read 35.7K   920   23  
In this article, I will explain what transparent lazy loading is and how it's implemented in NHibernate and Entity Framework.
  • LazyLoadingEntityFramework_src.zip
  • CreatTables_sql.zip
  • LazyLoadingNHibernate_src.zip
    • LazyLoadingNHibernate
      • Demo.Tests
      • Demo
      • LazyLoadingNHibernate.sln
      • LazyLoadingNHibernate.vsmdi
      • Library
        • Iesi.Collections.dll
        • NHibernate.dll
      • Local.testsettings
      • TestResults
        • Henry_LAPTOP 2012-01-13 20_27_04.trx
        • Henry_LAPTOP 2012-01-13 20_29_28.trx
        • Henry_LAPTOP 2012-01-13 20_31_42.trx
        • Henry_LAPTOP 2012-01-13 20_32_42.trx
        • Henry_LAPTOP 2012-01-13 20_36_10.trx
        • Henry_LAPTOP 2012-01-13 20_36_10
          • In
            • LAPTOP
          • Out
            • AgentRestart.dat
        • Henry_LAPTOP 2012-01-13 20_37_05.trx
        • Henry_LAPTOP 2012-01-13 20_37_19.trx
        • Henry_LAPTOP 2012-01-13 20_40_25.trx
        • Henry_LAPTOP 2012-01-13 20_43_37.trx
        • Henry_LAPTOP 2012-01-13 20_43_37
          • In
            • LAPTOP
          • Out
            • AgentRestart.dat
        • Henry_LAPTOP 2012-01-13 20_46_24.trx
        • Henry_LAPTOP 2012-01-13 20_46_24
          • In
            • LAPTOP
          • Out
            • AgentRestart.dat
        • Henry_LAPTOP 2012-01-13 20_50_33.trx
        • Henry_LAPTOP 2012-01-13 20_50_33
          • In
            • LAPTOP
          • Out
            • AgentRestart.dat
        • Henry_LAPTOP 2012-01-13 20_50_58.trx
        • Henry_LAPTOP 2012-01-13 20_50_58
          • In
            • LAPTOP
          • Out
            • AgentRestart.dat
        • Henry_LAPTOP 2012-01-13 20_56_53.trx
        • Henry_LAPTOP 2012-01-13 20_57_27.trx
        • Henry_LAPTOP 2012-01-13 20_57_57.trx
        • Henry_LAPTOP 2012-01-13 20_58_28.trx
        • Henry_LAPTOP 2012-01-13 20_58_28
          • In
            • LAPTOP
          • Out
            • AgentRestart.dat
        • Henry_LAPTOP 2012-01-13 21_01_34.trx
        • Henry_LAPTOP 2012-01-13 21_01_42.trx
        • Henry_LAPTOP 2012-01-13 21_02_01.trx
        • Henry_LAPTOP 2012-01-13 21_02_01
          • In
            • LAPTOP
          • Out
            • AgentRestart.dat
      • TraceAndTestImpact.testsettings
<#
//*********************************************************
//
//    Copyright (c) Microsoft. All rights reserved.
//    This code is licensed under the Microsoft Public License.
//    THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
//    ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
//    IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
//    PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
//
//*********************************************************
#>
<#@ template language="C#" debug="false" hostspecific="true"#>
<#@ include file="EF.Utility.CS.ttinclude"#><#@
 output extension=".cs"#><#

CodeGenerationTools code = new CodeGenerationTools(this);
MetadataTools ef = new MetadataTools(this);
MetadataLoader loader = new MetadataLoader(this);
CodeRegion region = new CodeRegion(this);

string inputFile = @"DemoEntityDataModel.edmx";
EdmItemCollection ItemCollection = loader.CreateEdmItemCollection(inputFile);
string namespaceName = code.VsNamespaceSuggestion();

EntityContainer container = ItemCollection.GetItems<EntityContainer>().FirstOrDefault();
if (container == null)
{
    return "// No EntityContainer exists in the model, so no code was generated";
}
#>
//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated from a template.
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

using System;
using System.Data.Objects;
using System.Data.EntityClient;

<#
if (!String.IsNullOrEmpty(namespaceName))
{
#>
namespace <#=code.EscapeNamespace(namespaceName)#>
{
<#
    PushIndent(CodeRegion.GetIndent(1));
}
#>
<#=Accessibility.ForType(container)#> partial class <#=code.Escape(container)#> : ObjectContext
{
    public const string ConnectionString = "name=<#=container.Name#>";
    public const string ContainerName = "<#=container.Name#>";

    #region Constructors

    public <#=code.Escape(container)#>()
        : base(ConnectionString, ContainerName)
    {
<#
        WriteLazyLoadingEnabled(container);
#>
    }

    public <#=code.Escape(container)#>(string connectionString)
        : base(connectionString, ContainerName)
    {
<#
        WriteLazyLoadingEnabled(container);
#>
    }

    public <#=code.Escape(container)#>(EntityConnection connection)
        : base(connection, ContainerName)
    {
<#
        WriteLazyLoadingEnabled(container);
#>
    }

    #endregion

<#
        region.Begin("ObjectSet Properties", 2);

        foreach (EntitySet entitySet in container.BaseEntitySets.OfType<EntitySet>())
        {
#>

    <#=Accessibility.ForReadOnlyProperty(entitySet)#> ObjectSet<<#=code.Escape(entitySet.ElementType)#>> <#=code.Escape(entitySet)#>
    {
        get { return <#=code.FieldName(entitySet) #>  ?? (<#=code.FieldName(entitySet)#> = CreateObjectSet<<#=code.Escape(entitySet.ElementType)#>>("<#=entitySet.Name#>")); }
    }
    private ObjectSet<<#=code.Escape(entitySet.ElementType)#>> <#=code.FieldName(entitySet)#>;
<#
        }

        region.End();

        region.Begin("Function Imports");

        foreach (EdmFunction edmFunction in container.FunctionImports)
        {
            var parameters = FunctionImportParameter.Create(edmFunction.Parameters, code, ef);
            string paramList = String.Join(", ", parameters.Select(p => p.FunctionParameterType + " " + p.FunctionParameterName).ToArray());
            if (edmFunction.ReturnParameter == null)
            {
                continue;
            }
            string returnTypeElement = code.Escape(ef.GetElementType(edmFunction.ReturnParameter.TypeUsage));

#>
    <#=Accessibility.ForMethod(edmFunction)#> ObjectResult<<#=returnTypeElement#>> <#=code.Escape(edmFunction)#>(<#=paramList#>)
    {
<#
            foreach (var parameter in parameters)
            {
                if (!parameter.NeedsLocalVariable)
                {
                    continue;
                }
#>

        ObjectParameter <#=parameter.LocalVariableName#>;

        if (<#=parameter.IsNullableOfT ? parameter.FunctionParameterName + ".HasValue" : parameter.FunctionParameterName + " != null"#>)
        {
            <#=parameter.LocalVariableName#> = new ObjectParameter("<#=parameter.EsqlParameterName#>", <#=parameter.FunctionParameterName#>);
        }
        else
        {
            <#=parameter.LocalVariableName#> = new ObjectParameter("<#=parameter.EsqlParameterName#>", typeof(<#=parameter.RawClrTypeName#>));
        }
<#
            }
#>
        return base.ExecuteFunction<<#=returnTypeElement#>>("<#=edmFunction.Name#>"<#=code.StringBefore(", ", String.Join(", ", parameters.Select(p => p.ExecuteParameterName).ToArray()))#>);
    }
<#
        }

        region.End();

#>
}
<#
if (!String.IsNullOrEmpty(namespaceName))
{
    PopIndent();
#>
}
<#
}
#>
<#+

private void WriteLazyLoadingEnabled(EntityContainer container)
{
   string lazyLoadingAttributeValue = null;
   string lazyLoadingAttributeName = MetadataConstants.EDM_ANNOTATION_09_02 + ":LazyLoadingEnabled";
   if(MetadataTools.TryGetStringMetadataPropertySetting(container, lazyLoadingAttributeName, out lazyLoadingAttributeValue))
   {
       bool isLazyLoading = false;
       if(bool.TryParse(lazyLoadingAttributeValue, out isLazyLoading))
       {
#>
        this.ContextOptions.LazyLoadingEnabled = <#=isLazyLoading.ToString().ToLowerInvariant()#>;
<#+
       }
   }
}
#>

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior)
United States United States
Senior Software Developer from New Jersey, USA

Have 15+ years experience on enterprise application development with various technologies.

Comments and Discussions