There is two way to map code first with DB related entities. The first is data annotation which is like setting attributes and the other one is fluent mapping. Fluent mapping is very powerful and flexible approach to map entities. The only downside of fluent mapping is incompatibility with client side validation where as MVC has inbuilt functionality to validate on client side with data annotation.
We will look into basic fluent mapping generation along with data annotation if present. Default data annotation is not compatible with Telerik DataAccess/OpenAccess. This article does not gives information about how fluent mapping works or how to generate it but auto generation of fluent mapping by any give model.
Pre-requisites for fluent generation
I have took help of two different libraries to generate fluent mapping for OpenAccess.
- MultiOutput.ttinclude (https://github.com/subsonic/SubSonic-3.0-Templates/blob/master/ActiveRecord/MultiOutput.ttinclude) : This is to generate multiple files through single T4 file.
- VisualStudioAutomationHelper.ttinclude (https://github.com/PombeirP/T4Factories/blob/master/T4Factories.Testbed/CodeTemplates/VisualStudioAutomationHelper.ttinclude) : This will help us in reading existing models and refactoring through EnvDte library.
Guide to be followed for generation:
Choose the path to include above files (In my case those are kept in T4Plugin):
<#@ include file="../../T4Plugin/VisualStudioAutomationHelper.ttinclude" #>
<#@ include file="../../T4Plugin/MultiOutput.ttinclude" #>
White-listing and black listing properties
var whiteListPropertyTypes = new List<string>(){};
var blackListedPropertyNames = new List<string>();
In whiteListPropertyTypes list, we can specify the custom types that need to be included. Like some enumeration types. In same way some properties could be excluded by help of blackListedPropertyNames list.
Listing classes for generation of fluent mapping
var codeClass in allClasses.OfType<CodeClass2>()
.Where(clas=> clas!=null && clas.FullName.StartsWith("T4FluentMapping.DomainModel") &&
!clas.FullName.EndsWith("MetadataSource"))
This code will list up all classes starts with T4FluentMapping.DomainModel and excludes class ends with MetadataSource.
That is all needed to generate basic fluent mapping. Here the all code goes:
-----------------------------------------------------------------------------------------------
<#@ template debug="true" hostSpecific="true" #>
<#@ output extension=".cs" #>
<#@ Assembly Name="EnvDTE" #>
<#@ Assembly Name="EnvDTE80" #>
<#@ Assembly name="System.ComponentModel.DataAnnotations" #>
<#@ import namespace="EnvDTE" #>
<#@ import namespace="EnvDTE80" #>
<#@ import namespace="System" #>
<#@ import namespace="System.Linq" #>
<#@ import namespace="System.Collections" #>
<#@ import namespace="System.Collections.Generic" #>
<#@ import namespace="System.ComponentModel.DataAnnotations" #>
<#@ import namespace="System.Text.RegularExpressions" #>
<#@ include file="../../T4Plugin/VisualStudioAutomationHelper.ttinclude" #>
<#@ include file="../../T4Plugin/MultiOutput.ttinclude" #>
<#
// get a reference to the project of this t4 template
var project = VisualStudioHelper.CurrentProject;
// get all class items from the code model
var allClasses = VisualStudioHelper.GetAllCodeElementsOfType(project.CodeModel.CodeElements, EnvDTE.vsCMElement.vsCMElementClass, false);
// TODO: Extra parameter type to get it listed
// Ex: Model.Enumeration.DbOperation
var whiteListPropertyTypes = new List<string>(){};
var blackListedPropertyNames = new List<string>();
// iterate all classes
foreach(var codeClass in allClasses.OfType<CodeClass2>()
.Where(clas=> clas!=null && clas.FullName.StartsWith("T4FluentMapping.DomainModel") &&
!clas.FullName.EndsWith("MetadataSource")))
{
var fileName=codeClass.Name+"Mapping.Generated.cs";
#>
namespace T4FluentMapping.Model.Mapping.FluentMapping
{
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated from a template and will be re-created if deleted
// with default values if executed.
// </auto-generated>
//------------------------------------------------------------------------------
using Telerik.OpenAccess.Metadata;
using Telerik.OpenAccess.Metadata.Fluent;
/// <summary>
/// Fluent mapping for <see cref="<#= codeClass.FullName#>"/>
/// </summary>
public partial class <#= codeClass.Name#>Mapping
: MappingConfiguration<<#= codeClass.FullName #>>
{
/// <summary>
/// Initializes a basic fluent mappings for <see cref="<#= codeClass.FullName#>" />
/// </summary>
public void InitializeBasicMappings()
{
this.MapType(map => new
{
<#
// iterate all properties
var allProperties = VisualStudioHelper.GetAllCodeElementsOfType(codeClass.Members, EnvDTE.vsCMElement.vsCMElementProperty, true);
foreach(EnvDTE.CodeProperty property in allProperties
.Where(prop=>(prop as CodeProperty2).ReadWrite == vsCMPropertyKind.vsCMPropertyKindReadWrite))
{
// for excluding property
var commentForFieldValue = ((property.Name == "FieldValue" && codeClass.Name == "SystemDataField" )
|| blackListedPropertyNames.Any(propName=>propName == property.Name)
)?"//":String.Empty;
if (IsPrimitive(property.Type) || whiteListPropertyTypes.Contains(property.Type.AsFullName))
{
#>
<#=commentForFieldValue#>map.<#=property.Name #>,
<#
}
#>
<#
}
#>
}).ToTable("<#= codeClass.Name #>");
// Data annotation mappings
<#
// For data annotation attribute mapping
foreach(EnvDTE.CodeProperty property in allProperties)
{
if(IsType(property.Type,typeof(bool)))
{
#>this.HasProperty(model => model.<#=property.Name#>).HasColumnType("bit");
<#
}
foreach(var attribute in GetAttributes(property))
{
if(attribute.Name == "Required")
{
#>this.HasProperty(model => model.<#=property.Name#>).IsNotNullable();
<#
}
if(attribute.Name == "MaxLength")
{
#>this.HasProperty(model => model.<#=property.Name#>).HasColumnType("varchar").HasLength(<#=attribute.Value#>);
<#
}
if(attribute.Name == "StringLength")
{
#>this.HasProperty(model => model.<#=property.Name#>).HasColumnType("varchar").HasLength(<#=attribute.Value#>);
<#
}
}
if(whiteListPropertyTypes.Contains(property.Type.AsFullName))
{
#>this.HasProperty(model => model.<#=property.Name#>);
<#
}
if(IsNullable(property.Type))
{
#>this.HasProperty(model => model.<#=property.Name#>).IsNullable();
<#
}
}#>
}
}
}
<#
SaveOutput(fileName);
DeleteOldOutputs();
}
#>
<#+
// Support C# and VB syntax
private static readonly Regex _unwrapNullableRegex = new Regex(@"^System.Nullable(<|\(Of )(?<UnderlyingTypeName>.*)(>|\))$");
private static Type[] _primitiveList;
private static void InitializePrimitives()
{
if(_primitiveList == null)
{
var types = new[]
{
typeof (Enum),
typeof (String),
typeof (Char),
typeof (Boolean),
typeof (Byte),
typeof (Int16),
typeof (Int32),
typeof (Int64),
typeof (Single),
typeof (Double),
typeof (Decimal),
typeof (SByte),
typeof (UInt16),
typeof (UInt32),
typeof (UInt64),
typeof (DateTime),
typeof (DateTimeOffset),
typeof (TimeSpan),
};
var nullTypes = from t in types
where t.IsValueType
select typeof (Nullable<>).MakeGenericType(t);
_primitiveList = types.Concat(nullTypes).ToArray();
}
}
/// <summary>
/// Determines whether the supplied CodeTypeRef represents a primitive .NET type, e.g.,
/// byte, bool, float, etc.
/// </summary>
public static bool IsPrimitive(CodeTypeRef codeTypeRef)
{
InitializePrimitives();
return _primitiveList.Any(item => item.FullName == codeTypeRef.AsFullName || _unwrapNullableRegex.Match(codeTypeRef.AsFullName).Success);
}
public static bool IsNullable(CodeTypeRef codeTypeRef)
{
return _unwrapNullableRegex.Match(codeTypeRef.AsFullName).Success;
}
public static IEnumerable<CodeAttribute> GetAttributes(CodeProperty codeProperty)
{
return codeProperty.Attributes.OfType<CodeAttribute>().ToList();
}
public static bool IsType<T>(CodeTypeRef codeTypeRef)
{
return IsType(codeTypeRef , typeof(T));
}
public static bool IsType(CodeTypeRef codeTypeRef, Type type)
{
return codeTypeRef.AsFullName == type.ToString() || codeTypeRef.AsFullName == "System.Nullable<"+ type.ToString()+ ">";
}
#>
-----------------------------------------------------------------------------------------------
We will look into basic fluent mapping generation along with data annotation if present. Default data annotation is not compatible with Telerik DataAccess/OpenAccess. This article does not gives information about how fluent mapping works or how to generate it but auto generation of fluent mapping by any give model.
Pre-requisites for fluent generation
I have took help of two different libraries to generate fluent mapping for OpenAccess.
- MultiOutput.ttinclude (https://github.com/subsonic/SubSonic-3.0-Templates/blob/master/ActiveRecord/MultiOutput.ttinclude) : This is to generate multiple files through single T4 file.
- VisualStudioAutomationHelper.ttinclude (https://github.com/PombeirP/T4Factories/blob/master/T4Factories.Testbed/CodeTemplates/VisualStudioAutomationHelper.ttinclude) : This will help us in reading existing models and refactoring through EnvDte library.
Guide to be followed for generation:
Choose the path to include above files (In my case those are kept in T4Plugin):
<#@ include file="../../T4Plugin/VisualStudioAutomationHelper.ttinclude" #>
<#@ include file="../../T4Plugin/MultiOutput.ttinclude" #>
White-listing and black listing properties
var whiteListPropertyTypes = new List<string>(){};
var blackListedPropertyNames = new List<string>();
In whiteListPropertyTypes list, we can specify the custom types that need to be included. Like some enumeration types. In same way some properties could be excluded by help of blackListedPropertyNames list.
Listing classes for generation of fluent mapping
var codeClass in allClasses.OfType<CodeClass2>()
.Where(clas=> clas!=null && clas.FullName.StartsWith("T4FluentMapping.DomainModel") &&
!clas.FullName.EndsWith("MetadataSource"))
This code will list up all classes starts with T4FluentMapping.DomainModel and excludes class ends with MetadataSource.
That is all needed to generate basic fluent mapping. Here the all code goes:
-----------------------------------------------------------------------------------------------
<#@ template debug="true" hostSpecific="true" #>
<#@ output extension=".cs" #>
<#@ Assembly Name="EnvDTE" #>
<#@ Assembly Name="EnvDTE80" #>
<#@ Assembly name="System.ComponentModel.DataAnnotations" #>
<#@ import namespace="EnvDTE" #>
<#@ import namespace="EnvDTE80" #>
<#@ import namespace="System" #>
<#@ import namespace="System.Linq" #>
<#@ import namespace="System.Collections" #>
<#@ import namespace="System.Collections.Generic" #>
<#@ import namespace="System.ComponentModel.DataAnnotations" #>
<#@ import namespace="System.Text.RegularExpressions" #>
<#@ include file="../../T4Plugin/VisualStudioAutomationHelper.ttinclude" #>
<#@ include file="../../T4Plugin/MultiOutput.ttinclude" #>
<#
// get a reference to the project of this t4 template
var project = VisualStudioHelper.CurrentProject;
// get all class items from the code model
var allClasses = VisualStudioHelper.GetAllCodeElementsOfType(project.CodeModel.CodeElements, EnvDTE.vsCMElement.vsCMElementClass, false);
// TODO: Extra parameter type to get it listed
// Ex: Model.Enumeration.DbOperation
var whiteListPropertyTypes = new List<string>(){};
var blackListedPropertyNames = new List<string>();
// iterate all classes
foreach(var codeClass in allClasses.OfType<CodeClass2>()
.Where(clas=> clas!=null && clas.FullName.StartsWith("T4FluentMapping.DomainModel") &&
!clas.FullName.EndsWith("MetadataSource")))
{
var fileName=codeClass.Name+"Mapping.Generated.cs";
#>
namespace T4FluentMapping.Model.Mapping.FluentMapping
{
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated from a template and will be re-created if deleted
// with default values if executed.
// </auto-generated>
//------------------------------------------------------------------------------
using Telerik.OpenAccess.Metadata;
using Telerik.OpenAccess.Metadata.Fluent;
/// <summary>
/// Fluent mapping for <see cref="<#= codeClass.FullName#>"/>
/// </summary>
public partial class <#= codeClass.Name#>Mapping
: MappingConfiguration<<#= codeClass.FullName #>>
{
/// <summary>
/// Initializes a basic fluent mappings for <see cref="<#= codeClass.FullName#>" />
/// </summary>
public void InitializeBasicMappings()
{
this.MapType(map => new
{
<#
// iterate all properties
var allProperties = VisualStudioHelper.GetAllCodeElementsOfType(codeClass.Members, EnvDTE.vsCMElement.vsCMElementProperty, true);
foreach(EnvDTE.CodeProperty property in allProperties
.Where(prop=>(prop as CodeProperty2).ReadWrite == vsCMPropertyKind.vsCMPropertyKindReadWrite))
{
// for excluding property
var commentForFieldValue = ((property.Name == "FieldValue" && codeClass.Name == "SystemDataField" )
|| blackListedPropertyNames.Any(propName=>propName == property.Name)
)?"//":String.Empty;
if (IsPrimitive(property.Type) || whiteListPropertyTypes.Contains(property.Type.AsFullName))
{
#>
<#=commentForFieldValue#>map.<#=property.Name #>,
<#
}
#>
<#
}
#>
}).ToTable("<#= codeClass.Name #>");
// Data annotation mappings
<#
// For data annotation attribute mapping
foreach(EnvDTE.CodeProperty property in allProperties)
{
if(IsType(property.Type,typeof(bool)))
{
#>this.HasProperty(model => model.<#=property.Name#>).HasColumnType("bit");
<#
}
foreach(var attribute in GetAttributes(property))
{
if(attribute.Name == "Required")
{
#>this.HasProperty(model => model.<#=property.Name#>).IsNotNullable();
<#
}
if(attribute.Name == "MaxLength")
{
#>this.HasProperty(model => model.<#=property.Name#>).HasColumnType("varchar").HasLength(<#=attribute.Value#>);
<#
}
if(attribute.Name == "StringLength")
{
#>this.HasProperty(model => model.<#=property.Name#>).HasColumnType("varchar").HasLength(<#=attribute.Value#>);
<#
}
}
if(whiteListPropertyTypes.Contains(property.Type.AsFullName))
{
#>this.HasProperty(model => model.<#=property.Name#>);
<#
}
if(IsNullable(property.Type))
{
#>this.HasProperty(model => model.<#=property.Name#>).IsNullable();
<#
}
}#>
}
}
}
<#
SaveOutput(fileName);
DeleteOldOutputs();
}
#>
<#+
// Support C# and VB syntax
private static readonly Regex _unwrapNullableRegex = new Regex(@"^System.Nullable(<|\(Of )(?<UnderlyingTypeName>.*)(>|\))$");
private static Type[] _primitiveList;
private static void InitializePrimitives()
{
if(_primitiveList == null)
{
var types = new[]
{
typeof (Enum),
typeof (String),
typeof (Char),
typeof (Boolean),
typeof (Byte),
typeof (Int16),
typeof (Int32),
typeof (Int64),
typeof (Single),
typeof (Double),
typeof (Decimal),
typeof (SByte),
typeof (UInt16),
typeof (UInt32),
typeof (UInt64),
typeof (DateTime),
typeof (DateTimeOffset),
typeof (TimeSpan),
};
var nullTypes = from t in types
where t.IsValueType
select typeof (Nullable<>).MakeGenericType(t);
_primitiveList = types.Concat(nullTypes).ToArray();
}
}
/// <summary>
/// Determines whether the supplied CodeTypeRef represents a primitive .NET type, e.g.,
/// byte, bool, float, etc.
/// </summary>
public static bool IsPrimitive(CodeTypeRef codeTypeRef)
{
InitializePrimitives();
return _primitiveList.Any(item => item.FullName == codeTypeRef.AsFullName || _unwrapNullableRegex.Match(codeTypeRef.AsFullName).Success);
}
public static bool IsNullable(CodeTypeRef codeTypeRef)
{
return _unwrapNullableRegex.Match(codeTypeRef.AsFullName).Success;
}
public static IEnumerable<CodeAttribute> GetAttributes(CodeProperty codeProperty)
{
return codeProperty.Attributes.OfType<CodeAttribute>().ToList();
}
public static bool IsType<T>(CodeTypeRef codeTypeRef)
{
return IsType(codeTypeRef , typeof(T));
}
public static bool IsType(CodeTypeRef codeTypeRef, Type type)
{
return codeTypeRef.AsFullName == type.ToString() || codeTypeRef.AsFullName == "System.Nullable<"+ type.ToString()+ ">";
}
#>
-----------------------------------------------------------------------------------------------
Comments
Post a Comment