Entity Framework 6 - Database First - Remove table names with prefixes

.net asp.net c# entity-framework entity-framework-6

Question

I have an existing database with tables that have a prefix

ex) - px_mytable1 - tx_mytable1

When I use entity framework to generate models from my database, the prefix is included in the model name..

ex) - public partial class px_mytable1 - public partial class tx_mytable1

How do I configure entity framework to remove the prefix from the model name?

Note: I am using an .edmx file to generate models from the database schema.

1
1
5/4/2016 12:57:21 PM

Accepted Answer

You have to do some changes in t4 template files(.tt). first o all in yourModelName.tt file create a variable like this in line 5,6,7 ... 13

var tablePerfix="px_";

search in this file and find <#=codeStringGenerator.NavigationProperty(navigationProperty)#> and replace it by

<#=codeStringGenerator.NavigationProperty(navigationProperty).Replace(tablePerfix,"")#>

foreach (var entity in typeMapper.GetItemsToGenerate<EntityType>
(itemCollection))
{
    fileManager.StartNewFile(entity.Name + ".cs");
    BeginNamespace(code);
#>

replace it by

foreach (var entity in typeMapper.GetItemsToGenerate<EntityType>
(itemCollection))
{
    fileManager.StartNewFile(entity.Name.Replace(tablePerfix,"") + ".cs");
    BeginNamespace(code);

and do that for following codes

<#=codeStringGenerator.EntityClassOpening(entity).Replace(tablePerfix,"")#>
// ...
public <#=code.Escape(entity).Replace(tablePerfix,"")#>()
// ...
this.<#=code.Escape(navigationProperty).Replace(tablePerfix,"")#> = new HashSet<<#=typeMapper.GetTypeName(navigationProperty.ToEndMember.GetEntityType()).Replace(tablePerfix,"")#>>();

if you have 2 prefix for tables in your DB you should use Replace method twice for each prefix

Finally yourModelName.Context.tt file create tablePrefix variable and change following code

<#=codeStringGenerator.DbSet(entitySet)#>

To

<#=codeStringGenerator.DbSet(entitySet).Replace(tablePerfix,"")#>
3
2/9/2017 7:17:30 AM


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