#
/*
* Sam Meacham (www.samscode.com)
* Template to auto generate configuations for (entity => dto) and (dto => entity).
* Now works with lazy loading! (See the .ForMember() parts of the configs)
*/
//
// CONFIG SECTION. Change these values to be specific to your project.
//
// This should be the relative path from this template to your .edmx file
string inputFile = "../PersonEntities.edmx";
// The namespace where your DTO classes are contained
string dtoClassNamespace = "Test.DataAccess.DTOs";
// If you have lazy loading enabled or not.
// NOTE: If you are using POCO entities, lazy loading is currently not supported with these templates.
// I'm not sure how to check if a navigation property has been lazy loaded or not already, with the POCO classes.
// If you are using the POCO classes, you'll have to disable lazy loading in your model.
bool modelHasLazyLoading = true;
#>
<#@ template language="C#" debug="false" hostspecific="true"#>
<#@ include file="EF.Utility.CS.ttinclude"#>
<#@ output extension=".cs"#>
<#
CodeGenerationTools code = new CodeGenerationTools(this);
MetadataLoader loader = new MetadataLoader(this);
EdmItemCollection ItemCollection = loader.CreateEdmItemCollection(inputFile);
string namespaceName = code.VsNamespaceSuggestion();
#>
using <#= dtoClassNamespace #>;
namespace <#= code.EscapeNamespace(namespaceName) #>
{
///
/// Currently only supports Navigation properties, not complex properties.
/// The .ForMember() calls prevent triggering lazy loading EF navigation properties. If an EntityReference or
/// EntityCollection has not been loaded, it will be ignored.
///
public static class AutoMapperConfig
{
private static bool s_isInit = false;
public static void CreateMappings()
{
if (s_isInit)
return;
s_isInit = true;
<#
foreach (EntityType entity in ItemCollection.GetItems().OrderBy(e => e.Name))
{
#>
// AutoMapper config for <#= code.Escape(entity) #> => <#=code.Escape(entity)#>Dto
AutoMapper.Mapper.CreateMap<<#= code.Escape(entity) #>, <#= code.Escape(entity) #>Dto>()<#
if (modelHasLazyLoading)
{
foreach (NavigationProperty navProperty in entity.NavigationProperties.Where(np => np.DeclaringType == entity))
{
// Collections
if (navProperty.ToEndMember.RelationshipMultiplicity == RelationshipMultiplicity.Many)
{
#>
.ForMember(dto => dto.<#= code.Escape(navProperty) #>,
options => options.MapFrom(obj => obj.<#=code.Escape(navProperty)#>.IsLoaded ? obj.<#=code.Escape(navProperty)#> : null))<#
}
else // Single instance
{
#>
.ForMember(dto => dto.<#= code.Escape(navProperty) #>,
options => options.MapFrom(obj => obj.<#=code.Escape(navProperty)#>Reference.IsLoaded ? obj.<#=code.Escape(navProperty)#> : null))<#
}
}
}
#>;
// Reverse config (dto => entity)
AutoMapper.Mapper.CreateMap<<#= code.Escape(entity) #>Dto, <#= code.Escape(entity) #>>();
<#
}
#>
}
}
}