I'm using EF 6.1 new feature - Code first from existing DB - and I'd like to add a foreign key in addition to each navigation property. I added the default T4 templates from nuget but I cannot figure out how to edit it. I guess it should be a quite common task, but I wasn't able to find any example... Thanks Matteo
You can modify the T4 templates, that are used for generating the entity classes following the instructions from here. Just follow the instructions from the comment of BriceLambson on Apr 28 at 6:22 PM
You need the following structure in your project:
The file EntityType.cs.t4 must contain the contents of the following link.
After that you can change the following part:
<#
}
foreach (var navigationProperty in entityType.NavigationProperties)
{
if (!first)
{
WriteLine(string.Empty);
}
else
{
first = false;
}
#>
public virtual <#= code.Type(navigationProperty) #> <#= code.Property(navigationProperty) #> { get; set; }
<#
}
#>
to something like this:
<#
}
foreach (var navigationProperty in entityType.NavigationProperties)
{
if (!first)
{
WriteLine(string.Empty);
}
else
{
first = false;
}
#>
public int <#= code.Property(navigationProperty) #>ID { get; set; }
[ForeignKey("<#= code.Property(navigationProperty) #>ID")]
public virtual <#= code.Type(navigationProperty) #> <#= code.Property(navigationProperty) #> { get; set; }
<#
}
#>
After that you can use - code first from existing database - to generate your entities.
Hope this helps
Instead of creating the directory structure by hand one can just install the nuget package EntityFramework.CodeTemplates.CSharp
as Matteo Sganzetta did