Reputation: 33
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;
}
Upvotes: 2
Views: 3127
Reputation: 26763
_context.Database.EnsureCreated()
See https://learn.microsoft.com/en-us/ef/core/api/microsoft.entityframeworkcore.infrastructure.databasefacade for details.
Upvotes: 1