11

estoy usando Entity Framework 4.3 Código primero con un inicializador base de datos personalizada de esta manera:¿Cómo puedo desactivar el uso de la tabla __MigrationHistory en Entity Framework 4.3 Code First?

public class MyContext : DbContext 
{ 
    public MyContext() 
    { 
     Database.SetInitializer(new MyContextInitializer()); 
    } 
} 

public class MyContextInitializer : CreateDatabaseIfNotExists<MyContext> 
{ 
    protected override void Seed(MyContext context) 
    { 
     // Add defaults to certain tables in the database 

     base.Seed(context); 
    } 
} 

Cada vez que mis cambios de modelo, editar mis POCO de asignaciones y de forma manual y actualizar mi base de datos manualmente.

Cuando ejecuto mi solicitud de nuevo, me sale este error:

Server Error in '/' Application.

The model backing the 'MyContext' context has changed since the database was created. Consider using Code First Migrations to update the database (http://go.microsoft.com/fwlink/?LinkId=238269).

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.InvalidOperationException: The model backing the 'MyContext' context has changed since the database was created. Consider using Code First Migrations to update the database (http://go.microsoft.com/fwlink/?LinkId=238269).

Usando EFProfiler, también nota los siguientes consultas en ejecución:

-- statement #1 
SELECT [GroupBy1].[A1] AS [C1] 
FROM (SELECT COUNT(1) AS [A1] 
     FROM [dbo].[__MigrationHistory] AS [Extent1]) AS [GroupBy1] 

-- statement #2 
SELECT TOP (1) [Project1].[C1]   AS [C1], 
       [Project1].[MigrationId] AS [MigrationId], 
       [Project1].[Model]  AS [Model] 
FROM (SELECT [Extent1].[MigrationId] AS [MigrationId], 
       [Extent1].[CreatedOn] AS [CreatedOn], 
       [Extent1].[Model]  AS [Model], 
       1      AS [C1] 
     FROM [dbo].[__MigrationHistory] AS [Extent1]) AS [Project1] 
ORDER BY [Project1].[CreatedOn] DESC 

Como puedo evitar esto?

Respuesta

10

Al principio estaba seguro de que era porque estableciste el inicializador predeterminado en el ctor pero al investigar un poco encontré que el inicializador no se ejecuta cuando se crea el contexto sino cuando consultas/añades algo por primera vez .

El inicializador proporcionado comprueba la compatibilidad del modelo para que no tenga suerte con ellos. Usted puede hacer fácilmente su propia inicialización como esta vez sin embargo:

public class Initializer : IDatabaseInitializer<Context> 
    { 

     public void InitializeDatabase(Context context) 
     { 
      if (!context.Database.Exists()) 
      { 
       context.Database.Create(); 
       Seed(context); 
       context.SaveChanges(); 
      } 
     } 

     private void Seed(Context context) 
     { 
      throw new NotImplementedException(); 
     } 
    } 

que no se debe comprobar compability y si la base de datos no se encuentra lo creará.

ACTUALIZACIÓN: "Contexto" debería ser el tipo de su aplicación de DbContext

+0

Gracias, Mikael. Tu solución parece funcionar. ¿Está seguro de que el valor predeterminado 'CreateDatabaseIfNotExists' no hace más que' if (! Context.Database.Exists()) {context.Database.Create(); Semilla (contexto); } '? –

+0

No estoy seguro, pero en el caso donde no existe db, generan exactamente el mismo sql de acuerdo con Sql Profiler al menos. –

+0

Acabo de descompilar EntityFramework.dll para ver qué hace. Eche un vistazo a esta esencia: https://gist.github.com/3017384 La parte más importante que falta es 'context.SaveChanges();' después de llamar a 'Seed (context);'. ¡Gracias por señalarme en la dirección correcta! –

Cuestiones relacionadas