实体框架动态表名部分

本文关键字:名部 动态 框架 实体 | 更新日期: 2023-09-27 18:08:39

表名包含year。它看起来像"Item_2015"Item_2014",有什么办法与它一起工作吗?我需要生成项目类,但它应该与年后缀db工作。由于

实体框架动态表名部分

您可以在上下文中添加一个构造函数,该构造函数接收后缀作为参数,并使用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);
    }
}