I'm trying a code first approach to creating multiple logging tables for a data archiver. The data that is being archived conforms to one model, but there are three different databases that the archiver queries data from. So I want to have three different SQL tables, one for each database.
ArchiveDataModel:
public class ArchiveDataModel
{
[Key]
public int ID { get; set; }
public string EventId { get; set; }
public string EventData { get; set; }
public string DateCreated { get; set; }
public string DateArchived { get; set; }
}
Here's my ApplicationDbContext:
public class ApplicationDbContext : DbContext
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options)
{
}
public DbSet<ArchiveDataModel> EventDataArchive_A { get; set; }
public DbSet<ArchiveDataModel> EventDataArchive_B { get; set; }
public DbSet<ArchiveDataModel> EventDataArchive_C { get; set; }
}
Running "add-migration" here creates a migration package for a table named "ArchiveDataModel." So I added this:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<ArchiveDataModel>()
.ToTable("EventDataArchive_A")
.ToTable("EventDataArchive_B")
.ToTable("EventDataArchive_C");
}
But this only creates a migration package for "EventDataArchive_C."
Would it be possible to use this one model to generate three identical tables via code-first approach?
Seems that both Fluent Api and Data Annotations could not solve this issue as far as these instruments target model class, not DbSet.
What you could do is to have a base class, 3 derived classes from a base class and 3 DbSet-s in your context each over corresponding derived model
public abstract class ArchiveDataModel
{
[Key]
public int ID { get; set; }
public string EventId { get; set; }
public string EventData { get; set; }
public string DateCreated { get; set; }
public string DateArchived { get; set; }
}
public class ArchiveDataModel_A : ArchiveDataModel { }
public class ArchiveDataModel_B : ArchiveDataModel { }
public class ArchiveDataModel_C : ArchiveDataModel { }
public class MyDbContext : DbContext
{
public MyDbContext(DbContextOptions<MyDbContext> options)
: base(options)
{ }
public DbSet<ArchiveDataModel_A> EventDataArchive_A { get; set; }
public DbSet<ArchiveDataModel_B> EventDataArchive_B { get; set; }
public DbSet<ArchiveDataModel_C> EventDataArchive_C { get; set; }
}