Note that there are some explanatory texts on larger screens.

plurals
  1. POMethod with generic type using runtime type
    primarykey
    data
    text
    <p>I'm trying to migrate a database with entity framework at runtime.<br> This is how you would usually do so:</p> <pre><code>Database.SetInitializer&lt;TContext&gt;(new MigrateDatabaseToLatestVersion&lt;TContext,TMigrationsConfiguration&gt;); } </code></pre> <p>However I do not know TContext or TMigrationsConfiguration until runtime.</p> <p>How would I execute this method with runtime types?</p> <hr> <p><em><strong>Update 1</em></strong></p> <p>@Alexander Balte's suggestion put me onto using the interface IDatabaseInitializer</p> <p>So this compiles without error:</p> <pre><code>foreach (IDatabaseInitializer&lt;DbContext&gt; initializer in moduleNeedingMigration.initializers) { System.Data.Entity.Database.SetInitializer(initializer); } </code></pre> <p>However i cannot do this:</p> <pre><code>public IEnumerable&lt;IDatabaseInitializer&lt;DbContext&gt;&gt; initializers { get { List&lt;IDatabaseInitializer&lt;Module1Context&gt;&gt; list = new List&lt;IDatabaseInitializer&lt;Module1Context&gt;&gt;(); MigrateDatabaseToLatestVersion&lt;Module1Context, Configuration&gt; init = new MigrateDatabaseToLatestVersion&lt;Module1Context, Configuration&gt;(); list.Add(init); return list;//Error cannot convert type List&lt;IDatabaseInitializer&lt;Module1Context&gt;&gt; to IEnumerable&lt;IDatabaseInitializer&lt;DbContext&gt;&gt; } } </code></pre> <p><strong>Note</strong> that Module1Context inherits DbContext</p> <hr> <p><em><strong>Update 2</em></strong></p> <p>This compiled:</p> <pre><code>return list.Cast&lt;IDatabaseInitializer&lt;UpfContext&gt;&gt;(); </code></pre> <p>However when i run the application I got this error:</p> <pre><code>System.Data.Entity.MigrateDatabaseToLatestVersion`2[Module1.Models.Module1Context,Module1.Migrations.Configuration]' to type 'System.Data.Entity.IDatabaseInitializer`1[System.Data.Entity.DbContext]'. </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload