TWilly
TWilly

Reputation: 4933

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

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.

Upvotes: 1

Views: 2607

Answers (2)

Kiarash Alinasab
Kiarash Alinasab

Reputation: 1013

You have to do some changes to the t4 template files(.tt). first o all in yourModelName.tt file add the following variable in in of the 5,6,7 ... 13 lines.

var tablePerfix="px_";

FInd the following code

 `<#=codeStringGenerator.NavigationProperty(navigationProperty)#>`

and replace it with

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

Find the following code

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

replace it with

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

Apply .Replacy(tablePerfix,"") like following to remove prefix from entities.

<#=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 prefixes for the tables in the DB you should use Replace method twice for each prefix

Finally, in yourModelName.Context.tt file add a variable called tablePrefix, and change following code

<#=codeStringGenerator.DbSet(entitySet)#>

To

<#=codeStringGenerator.DbSet(entitySet).Replace(tablePerfix,"")#>

Upvotes: 4

KanisXXX
KanisXXX

Reputation: 777

You can use the fluent API or data annotations to configure your classes so Code First can map the relationships between your tables. one way is to Override the OnModelCreating Method on Your DbContext Class, and there you can map your Classes To your Database table names

protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Class1>().ToTable("Table1");
        modelBuilder.Entity<Class2>().ToTable("Table2");
        modelBuilder.Entity<Class3>().ToTable("Table3");

        base.OnModelCreating(modelBuilder);
    }

This link may help you

Upvotes: -2

Related Questions