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

In order to add a foreign key in addition to each navigation property, I would like to use the new EF 6.1 capability called "Code first from existing DB." I downloaded the basic T4 templates from Nuget and uploaded them, but I'm not sure how to alter them. I suppose it should be a fairly typical work, but I couldn't find any examples. Thanks Matteo

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

Accepted Answer

By following the guidelines from here, you can alter the T4 templates that are used to create entity classes. Simply adhere to the recommendations in BriceLambson's comment from yesterday at 6:22 PM.

You require the following organization for your project:

  • CodeTemplates
    • EFModelFromDatabase
      • EntityType.cs.t4

The following link must be present in the file EntityType.cs.t4.

Following that, you can modify the following section:

<#
    }

    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 an instance of 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; }
<#
    }
#>

Following that, you can use code that is first generated from an existing database to create your entities.

Hope this is useful.

UPDATE

Installing the nuget package can be used in place of manually establishing the directory structure.EntityFramework.CodeTemplates.CSharp just like Matteo Sganzetta

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