简体   繁体   English

EF数据库上下文未清除

[英]EF Database Context not clearing

I have a program using Entity Framework where I'm dynamically selecting from a series of tables to display data. 我有一个使用Entity Framework的程序,在其中我从一系列表中动态选择来显示数据。 My tables within the database are named something along the lines of: 我在数据库中的表的命名方式如下:

Revisions2016
Revisions2017
Revisions2018

So far, I'm able to select different tables using Fluent API through calling: 到目前为止,我能够通过调用Fluent API选择不同的表:

modelBuilder.Entity<Revision>().ToTable("Revisions" + suffix);

within the OnModelCreating function of my database context. 在数据库上下文的OnModelCreating函数中。 My problem is that whenever I try creating a new database context through the following: 我的问题是,每当我尝试通过以下方法创建新的数据库上下文时:

public static void AccessRevisions(string tableName)
{
  using (var context = new RevisionsContext(tableName))
  {
    var revisionListing = context.Revisions.ToList();
    foreach (object o in revisionListing)
    {
      Revision r = o as Revision;
      Console.WriteLine(String.Format("ID: {0} NOTES: {1} AUTHOR: {2}", r.RevisionID, r.RevisionNotes, r.RevisionAuthor));
    }
  }
}

Although I've specified the lifetime of the database context as limited through "using", it always seems to end up selecting the old table rather then changing to the specified table on calling the function. 尽管我已通过“使用”来限制数据库上下文的生存期,但它似乎总是最终会选择旧表,而不是在调用函数时更改为指定的表。 So say if I specified 2016 and then 2017, the query results always seem to be 2016. 假设如果我指定2016年,然后指定2017年,则查询结果似乎始终是2016年。

I've tried forcing the initialisation of the context through using context.Database.Initialize(force: true); 我试图通过使用context.Database.Initialize(force: true);来强制初始化上下文context.Database.Initialize(force: true); and Database.SetInitializer(new DropCreateDatabaseAlways<RevisionsContext>()); Database.SetInitializer(new DropCreateDatabaseAlways<RevisionsContext>()); , but these don't seem to do anything. ,但这些似乎无能为力。 Would anyone be able to point me in the right direction on how to properly re-create my database context or dynamically switch tables? 有人能为我指出正确地重新创建数据库上下文或动态切换表的正确方向吗?

So after a while of searching, I think I've found a potential solution to my problems. 因此,经过一段时间的搜索,我认为我已经找到了解决问题的潜在方法。 I'll post what I've found here to help others who've been searching for the solution to the same problem I have. 我将在这里发布我发现的内容,以帮助那些一直在寻找与我同样的问题的解决方案的人。 With help from the blog post here by Benny Michielsen, I've constructed my context class as the following: 从博客文章帮助这里由尼Michielsen,我已经构造我的上下文类,如下所示:

  public class VAMPModelContext : DbContext
  {
    private VAMPModelContext(string _ConnectionString)
      : base(_ConnectionString)
    {
      Database.SetInitializer<VAMPModelContext>(null);
    }

    private VAMPModelContext(DbCompiledModel compiledModel, string connectionString)
      : base(compiledModel)
    {
      Database.SetInitializer<VAMPModelContext>(null);
      Database.Connection.ConnectionString = connectionString;
    }

    public static VAMPModelContext CreateContext(string suffix)
    {
      string connectionString = ConfigurationManager.ConnectionStrings["VAMPTest"].ConnectionString;
      VAMPModelContext dummyContext = new VAMPModelContext(connectionString);

      DbModelBuilder builder = new DbModelBuilder(DbModelBuilderVersion.Latest);
      builder.Configurations.Add(new EntityTypeConfiguration<VAMPModel>());

      // Construct model mapping for ORM
      string tableName = "VAMPModels" + suffix;
      builder.Entity<VAMPModel>().ToTable(tableName);

      // Compile ORM object, hard link connection
      DbConnection dummyConnection = dummyContext.Database.Connection;
      DbCompiledModel compiledModel = builder.Build(dummyConnection).Compile();

      // Finally make our database context
      dummyContext = new VAMPModelContext(compiledModel, connectionString);

      return dummyContext;
    }

    public virtual DbSet<VAMPModel> ModelsList { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
      // Adjust field properties for model
      modelBuilder.Entity<VAMPModel>()
          .Property(e => e.ModelCode)
          .IsUnicode(false);

      modelBuilder.Entity<VAMPModel>()
          .Property(e => e.PriceAUD)
          .HasPrecision(18, 0);

      base.OnModelCreating(modelBuilder);
    }
  }

Although we can only call OnModelCreating once through normal constructors, there's another constructor that accepts a compiled model to generate the context from scratch. 尽管我们只能通过普通的构造函数调用一次OnModelCreating,但是还有另一个构造函数接受编译的模型以从头开始生成上下文。 Hence, if we construct our own model and pass it through, we can in a sense "re-construct" the database context. 因此,如果我们构建自己的模型并将其传递,则可以在某种意义上“重新构建”数据库上下文。 From this class, we can simply call on it like this: 从此类中,我们可以像这样简单地调用它:

using(var context = VAMPModelContext.CreateContext("2016"))
{
  var modelsListing = context.ModelsList.ToList();
  foreach (object o in modelsListing)
  {
    VAMPModel m = o as VAMPModel;
    Console.WriteLine(String.Format("MODEL ID: {0} MODEL CODE: {1} PRICE: {2}", m.ModelID, m.ModelCode, m.PriceAUD));
  }
  context.Dispose();
}

I haven't tested the effects of all CRUD operations, but insertion and querying seems to work just fine. 我还没有测试所有CRUD操作的效果,但是插入和查询似乎可以正常工作。 Hope this helps anyone who's been searching for a solution to the Entity-Framework dynamic table mapping approach I've been. 希望这对一直在寻找我一直使用的Entity-Framework动态表映射方法的解决方案的人有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM