1

I have to create a table in code. The problem is, that I'm not allowed to use migrations. Application should check on start, whether the tables exist and add them on demand.

I have a very basic implementation of DbContext which is created by calling this method:

    public static ConfigurationDbContext CreateRemoteContext(string nameOrConnectionString)
    {
        var context = new ConfigurationDbContext(nameOrConnectionString);

        context.Configuration.ProxyCreationEnabled = false;
        context.Configuration.LazyLoadingEnabled = false;
        context.Configuration.AutoDetectChangesEnabled = false;

        return context;
    }

And a configuration container, which gets passed to the rest parts of the application. It contains arrays for every table, that get loaded like this:

    using (var dbContext = ConfigurationDbContext.CreateRemoteContext(App.Database.DbConnectionName))
    {
        var result = new ConfigurationContainer
        {
            ExistingTableEntities = dbContext.ExistingEntities.ToArray(),
            ...
            NotExistingTableEntities = dbContext.NotExistingTableEntities.ToArray()
        };
        ...
    }

Here all of the entities get loaded to the configuration container. While trying to access a not existing table, is predictably throws an exception.

How can I check, whether the table exists and create it on demand without migration?

Arli Chokoev
  • 521
  • 6
  • 22
  • 1
    Are you not allowed to use migrations because you have an existing database that isn't managed by EF? If that's the case, I would recommend using upgrade SQL scripts with the required steps and then using `_context.Database.ExecuteSQL` to run the scripts.. – Neil May 28 '20 at 08:22
  • What do you mean by that you can't use migrations? – Guru Stron May 28 '20 at 08:22
  • 2
    Check out this answer https://stackoverflow.com/a/45795873/11350283 – devcrp May 28 '20 at 08:23
  • @Neil yep, that's appropriate in my case. If you post an answer, I'll accept it. – Arli Chokoev May 28 '20 at 08:29
  • @devcrp this looks nice, but is for EF Core. – Arli Chokoev May 28 '20 at 08:30
  • Code-first's main driver is to simplify database development by having the computer _do all the heavy lifting_. i.e. taking care of the schema so you don't have to. To not use EF Migrations and do so manually via code arguably defeats the purpose of code-first. Perhaps you should consider using _Data Tier Applications; SSDT projects_ and _deployment via DACPACs_. DACPACs require zero coding and can do many things EF Migrations can't do easily. Staged deployments comes to mind –  May 28 '20 at 09:00

0 Answers0