How can I create database table using EF Core at run time?

asp.net-core asp.net-mvc entity-framework entity-framework-core

Question

I am new to ASP.NET Core. I am using VS2017 ASP.NET Core with EF Core to build the app that allows me to manage the daily purchase orders which are kept in a table in a database.

On the web there is an input textbox that allows me to enter the table name and when I click the Create button, the new table will be created. I will create a new table every day e.g. "Order25072017", "Order26072017", .. so on.

1) How can I create new table in asp.net Core MVC using EF core programmatically?

Those new tables use the same "Order" model/schema and the code to get the order list is "_context.Order25072017.ToList();". I am planning to create the dropdown with a list of table names. When selected, it will allow me to get the order list from the selected table.

2) What do I need to do in OnModelCreating()? 3) How can I change the table name in my query e.g. _context.{newtable}.ToList() at the run time?

The DB Context :

public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
    public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
        : base(options)
    {
    }

    public DbSet<Order> Order25072017 { get; set; }

    protected override void OnModelCreating(ModelBuilder builder)
    {
        base.OnModelCreating(builder);
    }
}

The Model :

public class Order
{
    public int ID { get; set; }
    [Required]
    public string Product  { get; set; }
    public int Price { get; set; }
    public int Discount { get; set; }
}

The constructor in OrderController:

private readonly ApplicationDbContext _context;
public OrderController(ApplicationDbContext context)
{
    _context = context;
}
1
2
7/25/2017 8:38:41 AM

Popular Answer

0
7/25/2017 3:04:54 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow