POCO T4

With EF4 features CTP1, we have a great POCO template which is divided in two tt files to allow us to have the entitiy POCO classes and the context in different projects.


It’s very very cool.


However, I think that it’s a shame not to have an interface for the context particularly to mock it.


So I change the .Context.tt like this:


 


<#@ template language=”C#” debug=”false” hostspecific=”true”#>
<#@ include file=”EF.Utility.ctp.CS.ttinclude”#><#@
output extension=”.cs”#><#
// Copyright (c) Microsoft Corporation.  All rights reserved.


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


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


TemplateFileManager fileManager = TemplateFileManager.Create(this);
EntityContainer container = ItemCollection.GetItems<EntityContainer>().FirstOrDefault();
if (container == null)
{
    return “// No EntityContainer exists in the model, so no code was generated”;
}


// Emit Entity Types
    string interfaceName = “I” + code.Escape(container);
    fileManager.StartNewFile(interfaceName + “.cs”);
#>
using System;
using System.Collections.Generic;
using System.Data.Objects;
using System.Data.EntityClient;
using Entities;


<#
if (!String.IsNullOrEmpty(namespaceName))
{
#>
namespace <#=code.EscapeNamespace(namespaceName)#>
{
<#
    PushIndent(CodeRegion.GetIndent(1));
}
#>
<#=Accessibility.ForType(container)#> interface <#=interfaceName#>
{
<#
        foreach (EntitySet entitySet in container.BaseEntitySets.OfType<EntitySet>())
        {
#>
    IObjectSet<<#=code.Escape(entitySet.ElementType)#>> <#=code.Escape(entitySet)#> { get; }
<#
        }
#>
<#
        if (container.FunctionImports.Any())
        {
#>


<#
        }
        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));


#>
    IEnumerable<<#=returnTypeElement#>> <#=code.Escape(edmFunction)#>(<#=paramList#>);
<#
        }
#>
}
<#
if (!String.IsNullOrEmpty(namespaceName))
{
    PopIndent();
#>
}
<#
}
    fileManager.WriteFiles();
#>
//——————————————————————————
// <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.Collections.Generic;
using System.Data.Objects;
using System.Data.EntityClient;
using Entities;


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


    #region Constructors


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


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


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


    #endregion


<#
        region.Begin(“ObjectSet Properties”);


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


    <#=AccessibilityAndVirtual(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)#>;
    IObjectSet<<#=code.Escape(entitySet.ElementType)#>> <#=interfaceName#>.<#=code.Escape(entitySet)#>
    {
        get { return <#=code.Escape(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));


#>
    <#=AccessibilityAndVirtual(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()))#>);
    }
    IEnumerable<<#=returnTypeElement#>> <#=interfaceName#>.<#=code.Escape(edmFunction)#>(<#=paramList#>)
    {
        return <#=code.Escape(edmFunction)#>(<#=String.Join(“, “, parameters.Select(p => p.FunctionParameterName).ToArray())#>);
    }
<#
        }


        region.End();
#>
}
<#
if (!String.IsNullOrEmpty(namespaceName))
{
    PopIndent();
#>
}
<#
}
#>
<#+
string AccessibilityAndVirtual(string accessibility)
{
    if (accessibility != “private”)
    {
        return accessibility + ” virtual”;
    }


    return accessibility;
}
#>


 


Enjoy [:)]

This entry was posted in 10511, 10550, 7671, 7674. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>