How to Add Table Prefix In Entity Framework Code First Globally?
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));
}
This works with EF Core 3.1+
Add a reference to the package Microsoft.EntityFrameworkCore.Relational
.
foreach (IMutableEntityType entity in modelBuilder.Model.GetEntityTypes())
{
entity.SetTableName("PE" + entity.GetTableName());
}
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));
}