如何首先在全局实体框架代码中添加表前缀?

Ron*_*eng 12 entity-framework

我想用像'pe_'这样的前缀添加数据库中的所有表,然后类和表之间的映射将是这样的:Category(pe_Category),Product(pe_Product)等.

我知道只用一张地图,我可以这样做:

[Table("pe_Category")]
public class Category
{
    public int CategoryId { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

但我不喜欢它,因为可能有数百个实体.

所以我找到了一种全局添加前缀的方法,就像这样:

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 ;
Run Code Online (Sandbox Code Playgroud)

有人可以帮帮我吗?

Ron*_*eng 23

现在我找到了一个实体框架6 alpha的解决方案:

1)创建一个名为"DefaultTableConvention"的类:

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

2)在DbContext中,添加以下代码:

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Conventions.Add<DefaultTableConvention>();
    }
Run Code Online (Sandbox Code Playgroud)

这就是全部,它将影响在DbContext中添加的所有实体.详情:http://entityframework.codeplex.com/wikipage?title = Custom%20Conventions

更新: 现在使用EF6,有一种更简单的方法,称为"轻量级配置",这是代码:

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


小智 12

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

仅适用于ef6-beta-1 ; Microsoft将实体更改为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));
 }
Run Code Online (Sandbox Code Playgroud)


Bea*_*uit 5

这适用于 EF Core 3.1+

添加对包的引用Microsoft.EntityFrameworkCore.Relational

foreach (IMutableEntityType entity in modelBuilder.Model.GetEntityTypes())
{
   entity.SetTableName("PE" + entity.GetTableName());
}
Run Code Online (Sandbox Code Playgroud)