Entity Framework 6.1 Code first from existing DB - add foreign key to T4 template

ef-code-first entity-framework entity-framework-6 t4

Question

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

1
0
5/4/2017 4:58:18 PM

Accepted Answer

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:

  • CodeTemplates
    • EFModelFromDatabase
      • EntityType.cs.t4

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

UPDATE

Instead of creating the directory structure by hand one can just install the nuget package EntityFramework.CodeTemplates.CSharp as Matteo Sganzetta did

1
6/17/2014 1:01:09 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow