如何在实体框架代码中首先在全球添加表前缀? [英] How to Add Table Prefix In Entity Framework Code First Globally?
问题描述
我想用数据库中的所有表添加一个前缀,如pe_,那么类和表之间的映射就像这样:Category(pe_Category),Product(pe_Product)等。
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 ;
任何人都可以帮助我?
推荐答案
现在我找到一个实体框架6 alpha的解决方案:
Now I've find a solution with entity framework 6 alpha:
1)创建一个名为DefaultTableConvention的类:
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)在DbContext中,添加以下代码:
2) In the DbContext, add the code below:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Add<DefaultTableConvention>();
}
这就是,它会影响在DbContext中添加的所有实体。详情: http://entityframework.codeplex.com/wikipage?title=Custom%20公约
And that's all, It will affect all entities added in the DbContext. Detail:http://entityframework.codeplex.com/wikipage?title=Custom%20Conventions
更新:
现在使用EF6,有一种更简单的方法,称为轻量级配置,这里是代码:
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));
}
这篇关于如何在实体框架代码中首先在全球添加表前缀?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!