Home > Blockchain >  EF Core 6.0.2 || Create table dynamically at run time with custom name
EF Core 6.0.2 || Create table dynamically at run time with custom name

Time:02-21

I have an entity class with 5 properties. See the class Person as an example:

public class Person
{
    public int Id{ get; set;} 

    [Required]
    public string Name{ get; set;}

    [Required]
    public string Address{ get; set;}

    [Required]
    public string EmailAddress{ get; set;}

    [Required]
    public string MobileNumber { get; set;}
}

My requirement is: when an admin creates a group and provides the name, I have to create a new table with the above model class' columns with the name as provided by the admin.

So if admin enters a name like DelhiPerson, then a table should be created in the database with name DelhiPerson with the same columns as shown in the above Person class.

I am using Entity Framework Core 6.0.2

I tried to Google but haven't found any relevant reference. Any reference or tutorial will be helpful.

CodePudding user response:

I did it through ADO.NET capabilities provided by EF Core.

using(var cmd = context.Database.GetDbContext().CreateCommand())
{
   cmd.CommandText = "Create Table SQL Statement here";
   context.Database.OpenConnection();
   var result = cmd.ExecuteNonQuery();
}
  • Related