I create dynamically table when website is active with this code:
public void CreateTable(string tableName, string field1, double field2, ...)
{
string Raw = string.Format("CREATE TABLE [{0}] ([ID] UNIQUEIDENTIFIER NOT NULL, [{1}] NVARCHAR (MAX) NOT NULL, [{2}] FLOAT NOT NULL, ..., , CONSTRAINT[PK_{0}] PRIMARY KEY CLUSTERED([ID] ASC);", tableName, field1, field2);
_context.Database.ExecuteSqlRaw(Raw);
_context.SaveChanges();
}
Now I want run query SQL select something like this::
private readonly ApplicationDbContext _context;
public HomeController(ApplicationDbContext context)
{
_context = context;
}
public void List(string tableName)
{
string Raw = string.Format("SELECT * FROM [{0}];", tableName);
var table = _context.Database.ExecuteSqlRaw(Raw);
//--- Do something with table here
}
NOTE: I try using reflection like this:
var table = _context.GetType().GetProperty(tableName).GetValue(_context) as IQueryable;
But not working and return NULL.
I'm still a newbie on C#, really appreciate if you can show me example based on this code.
"SELECT * FROM dbo.[{0}]"
. I'm assuming the schema of newly created tables is in dbo.