使用自定义表名创建重复实体框架模型。可能的缓存问题

时间:2016-10-17 10:38:41

标签: c# sql sql-server entity-framework

我编写了一个控制台应用程序,可以按月将数据归档到单独的SQL表中。每个表都具有相同的模式,但名称不同,时间戳不同。

e.g。读物_201610,读物_201609

我想迭代几个月,创建和处理DbContext,每次将Readings类指向不同的表名。出于某种原因,我的方法适用于第一次创建数据库,但在第二次迭代中似乎没有更改表名,即使上下文已被隐式处理并应重新创建。

下面是DbContext本身的修剪代码,接受表名作为参数的表配置以及在循环中初始化上下文的程序。任何有关失败原因的见解都会很棒。

作为旁注,我真的更希望这不要成为关于归档技术的讨论。我相信这是实体框架缓存的某些方面的错误,我真的很感激解决方法。

DbContext:

public class ReadingContext : DbContext
{
    private readonly string tablePrefix;

    public ReadingContext(string tablePrefix) : base("name=ArchiveDatabase")
    {            
        this.tablePrefix = tablePrefix;
    }

    public DbSet<Reading> BackupReadings { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Configurations.Add(new BackupReadingsConfiguration(tablePrefix));
        base.OnModelCreating(modelBuilder);
    }
}

表格配置:

public class BackupReadingsConfiguration : EntityTypeConfiguration<Reading>
{
    public BackupReadingsConfiguration(string tablePrefix)
    {
        // Map the table name
        string tableName = "Readings";

        if (!string.IsNullOrEmpty(tablePrefix))
        {
            tableName = string.Format("{0}_{1}", tableName, tablePrefix);
        }

        this.ToTable(tableName);
    }
}

该计划:

    public static void Main(string[] args)
    {        
        string _tablePrefix;
        DateTime _startDateTime = Properties.Settings.Default.StartDate;
        DateTime _endDateTime = Properties.Settings.Default.EndDate;

        int _year = _startDateTime.Year;
        int _month = _startDateTime.Month;

        while (new DateTime(_year, _month, 1, 0, 0, 0) < _endDateTime.AddDays(1))
        {
            _tablePrefix = string.Concat(_year.ToString("D4"), _month.ToString("D2"));

            using (var readingContext = new ReadingContext(_tablePrefix))
            {
                // Do Something
                // First DbContext creation has correct table name, all subsequent DbContext creations the table name remains the same as the first.
            }

            _month = ++_month % 13;

            if (_month % 13 == 0)
            {
                _year = ++_year;
                _month = ++_month;
            }
        }
    }

1 个答案:

答案 0 :(得分:0)

我通常不会提倡这种解决方案,但是对于一次性使用控制台应用程序和数据库上的操作是基本的,并且对EF创建的查询的唯一更改是表名更改。我决定使用一个拦截器。实际上使用了Eric Chhun提供的解决方案here