Ok, this question is quite old but still I'd like to share my solution to this.
What I did is to modify the T4 template in order to add a partial method to all generated entities and to call it from the constructor.
This partial method is implemented in an extended partial class which you will manually create for each entity you need to set default values.
Note: I'm using EF6
Short steps:
1) Modify the T4 template to include a partial method like this:
partial void OnCreationComplete();
2) Modify the T4 template to invoke that method in the constructor
OnCreationComplete();
3) Create a partial class for those entities which you need to set a default property and implement the OnCreationComplete method:
partial void OnCreationComplete()
{
PropertyFoo = "Bar";
}
Here is the complete code:
T4 Template
// You might want to remove the IF statement that excludes the constructor generation for entities without collection and complex entities...
<#
var propertiesWithDefaultValues = typeMapper.GetPropertiesWithDefaultValues(entity);
var collectionNavigationProperties = typeMapper.GetCollectionNavigationProperties(entity);
var complexProperties = typeMapper.GetComplexProperties(entity);
#>
public <#=code.Escape(entity)#>()
{
<#
foreach (var edmProperty in propertiesWithDefaultValues)
{
#>
<#=code.Escape(edmProperty)#> = <#=typeMapper.CreateLiteral(edmProperty.DefaultValue)#>;
<#
}
foreach (var navigationProperty in collectionNavigationProperties)
{
#>
<#=code.Escape(navigationProperty)#> = new HashSet<<#=typeMapper.GetTypeName(navigationProperty.ToEndMember.GetEntityType())#>>();
<#
}
foreach (var complexProperty in complexProperties)
{
#>
<#=code.Escape(complexProperty)#> = new <#=typeMapper.GetTypeName(complexProperty.TypeUsage)#>();
<#
}
#>
OnCreationComplete();
}
partial void OnCreationComplete();
Example of generated class:
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated from a template.
//
// Manual changes to this file may cause unexpected behavior in your application.
// Manual changes to this file will be overwritten if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace MyTest.DAL
{
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
public partial class Foo
{
public Foo()
{
OnCreationComplete();
}
partial void OnCreationComplete();
public string MyPropertyFoo { get; set; }
}
}
Extended partial class
public partial class Foo
{
partial void OnCreationComplete()
{
MyPropertyFoo = "Bar";
}
}
Hope it helps someone...