实体框架动态表名称部分

时间:2015-08-18 19:57:31

标签: c# entity-framework

我们有表名包括年。看起来像" Item_2015" " Item_2014"有没有办法与ef合作?我需要生成Item类,但它应该与db的年后缀一起使用。感谢

1 个答案:

答案 0 :(得分:2)

您可以在上下文中添加一个接收后缀作为参数的构造函数,并使用Fluent Api映射表的名称

public class Item
{
  //...
}

public class YourContext: DbContext 
{
    private string suffix="_2015";

    public SchoolDBContext(string _suffix): base() 
    {
       this.suffix=_suffix;
    }

    public DbSet<Item> Items{ get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
         // Map an Entity Type to a Specific Table in the Database
         modelBuilder.Entity<Item>().ToTable("Item"+suffix);

        base.OnModelCreating(modelBuilder);
    }
}