Zinger
Zinger

Reputation: 9

Dynamic tables in Entity Framework

The table has to be created dynamically. The table name is dynamic (is sent to API) and columns are static. Every time api is called, a new table is been created with different name.

Is it possible to do that in Entity Framework? If so - how? DB is Posstgress. Thanks

ADO is not the accepted way. I need to do it with Entity Framework. I tried to write migration that will be activated just when API is called. But it seems that migration can run only when running first.

Upvotes: 0

Views: 558

Answers (1)

David Browne - Microsoft
David Browne - Microsoft

Reputation: 89091

If you have a bunch of tables with the same columns and you want to switch between them at runtime, you can use SQL Queries.

var blogs = context.Blogs
    .FromSql($"SELECT * FROM {QuoteName(tableName)}")
    .ToList();

where QuoteName prevents SQL Injection attacks. This one is for SQL Server:

private static string QuoteName(string identifier)
{
    var sb = new StringBuilder(identifier.Length + 3, 1024);
    sb.Append('[');
    foreach (var c in identifier)
    {
        if (c == ']')
            sb.Append(']');
        sb.Append(c);
    }
    sb.Append(']');
    return sb.ToString();
}

Upvotes: 1

Related Questions