Home > Net >  Entity Framework create multiple tables at runtime C#
Entity Framework create multiple tables at runtime C#

Time:11-22

I try to get familiarized with EF using Sqlite.

I managed to create a model and based on that model using migrations I created a table.

My question is how I can create multiple tables of same model?

Example of model:

public class Blog
{
    public int BlogId { get; set; }
    public string Url { get; set; }
}

Example of my application db context:

public class ApplicationDbContext:DbContext
{
    public string DbPath { get; private set; }

    public DbSet<Blog> Blogs { get; set; }

    public ApplicationDbContext()
    {
        DbPath = $"HelloBlog.db";
    }

    protected override void OnConfiguring(DbContextOptionsBuilder options)
       => options.UseSqlite($"Data Source={DbPath}");

}

My question is how can I add new tables at runtime, ex. Blog_{Date}?

Since I don't know in advance how many tables I will create.

CodePudding user response:

My question is how can I add new tables at runtime, ex. Blog_{Date}? Since I don't know in advance how many tables I will create.

Your data management approach is flawed; you're using a table name to store data that should be stored in a column

Have a PostedDate column or similar in your Blogs table, store whatever data you were going to encode into the table name, into the column instead. Index the column

Whatever you were thinking of doing before like:

SELECT * FROM Blog_2000_01_01
SELECT * FROM Blog_2000_01_02

Ought to be done like:

SELECT * FROM Blog WHERE PostedDate = '2000-01-01'
SELECT * FROM Blog WHERE PostedDate = '2000-01-02'

In EF terms it's hence:

context.Blog.Where(b => b.PostedDate == new DateTime(2000,1,1))
context.Blog.Where(b => b.PostedDate == new DateTime(2000,1,2))
  • Related