Skip to content

Instantly share code, notes, and snippets.

@AdamLJohnson
Created January 31, 2012 17:49
Show Gist options
  • Save AdamLJohnson/1711821 to your computer and use it in GitHub Desktop.
Save AdamLJohnson/1711821 to your computer and use it in GitHub Desktop.
DBContext T4 Template changes for Key Required StringLength Attributes
// Add at the top with the other Usings
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
//Add following methods inside the file
private bool IsNullable(TypeUsage usage)
{
return (bool)usage.Facets.First(facet => facet.Name == "Nullable").Value;
}
private bool HasMaxLength(TypeUsage usage)
{
if (usage.Facets.Any(facet => facet.Name == "MaxLength"))
{
return true;
}
else
{
return false;
}
}
private string MaxLength(TypeUsage usage)
{
if (usage.Facets.First(facet => facet.Name == "MaxLength").Value.ToString() == "Max")
{
return "[DataType(DataType.MultilineText)]";
}
else
{
return String.Format("[StringLength({0})]", usage.Facets.First(facet => facet.Name == "MaxLength").Value.ToString());
}
}
string AddSpacesToFields(string text)
{
if (text == "UAID")
{
return text;
}
if (string.IsNullOrEmpty(text))
return "";
StringBuilder newText = new StringBuilder(text.Length * 2);
newText.Append(text[0]);
for (int i = 1; i < text.Length; i++)
{
if (char.IsUpper(text[i]))
{
if (text[i - 1].ToString() + text[i].ToString() == "ID")
{
}
else
{
newText.Append(' ');
}
}
newText.Append(text[i]);
}
return newText.ToString();
}
//Add the following lines inside the WriteProperty(CodeGenerationTools code, EdmProperty edmProperty) method
MetadataTools ef = new MetadataTools(this);
if(ef.IsKey(edmProperty)) { #>
[Key]
<#+ } if (!IsNullable(edmProperty.TypeUsage)) { #>
[Required]
<#+ } if(HasMaxLength(edmProperty.TypeUsage)) { #>
<#=MaxLength(edmProperty.TypeUsage) #>
<#+ } #>
[Display(Name = "<#=AddSpacesToFields(edmProperty.Name)#>")]
<#+
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment