How to Add Table Prefix In Entity Framework Code First Globally?

entity-framework

Question

I want to add all tables in the database with a prefix like 'pe_', then the mapping between a class and a table will be like this: Category(pe_Category), Product(pe_Product), etc.

I know that with one single map, i can do like this:

[Table("pe_Category")]
public class Category
{
    public int CategoryId { get; set; }
}

But I don't like it cause there maybe have hundreds of entities.

So I'm finding a way to add the prefix globally, just like this:

public class Category
{
    public int CategoryId { get; set; }
}

public class Product
{
    public int ProductId { get; set; }
}

// Global config, will affect all entities
table.Name = "pe_" + Class.TypeName ;

Anybody can help me?

1
13
9/29/2012 2:05:17 AM

Accepted Answer

Now I've find a solution with entity framework 6 alpha:

1) Create a class named "DefaultTableConvention":

public class DefaultTableConvention
: IConfigurationConvention<Type, EntityTypeConfiguration>
{
    public void Apply(
        Type type,
        Func<EntityTypeConfiguration> configuration)
    {            
        configuration().ToTable("PE_" + type.Name);
    }
}

2) In the DbContext, add the code below:

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Conventions.Add<DefaultTableConvention>();
    }

And that's all, It will affect all entities added in the DbContext. Detail:http://entityframework.codeplex.com/wikipage?title=Custom%20Conventions

Update: Now with EF6, there's an easier way, which is called "Lightweight Configuration", here's the code:

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Types().Configure(entity => entity.ToTable("PE" + entity.ClrType.Name));
    }
23
9/30/2014 10:09:13 PM

Popular Answer

protected override void OnModelCreating(DbModelBuilder modelBuilder)
 {
     modelBuilder.Entities().Configure(entity 
      => entity.ToTable("PE" + entity.ClrType.Name));
 }

only works on ef6-beta-1; Microsoft changed Entities to Types from ef6-rc1

http://blogs.msdn.com/b/adonet/archive/2013/08/21/ef6-release-candidate-available.aspx#10444012

protected override void OnModelCreating(DbModelBuilder modelBuilder)
 {
     modelBuilder.Types().Configure(entity 
      => entity.ToTable("PE" + entity.ClrType.Name));
 }


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