两个相同的生成数据库,包含实体框架6

时间:2016-04-19 12:53:37

标签: c# database entity-framework integration-testing

我已经使用Entity Framework 6构建了一个应用程序,创建了一些从数据库中插入提取数据的方法,现在我想为生产和调试环境测试它。

为了确保一切正常,我的调试数据库应该删除我测试的所有数据,而我的生产应该保留其数据。

我有两个项目:MyApp.DatabaseMyApp.Database.Test,每个项目的app.config文件都有一个连接字符串,程序加载如下:

public DatabaseContext() : base("name=MyDB")
{
    System.Data.Entity.Database.SetInitializer<DatabaseContext>(new CreateDatabaseIfNotExists<DatabaseContext>()); 
}

和连接字符串,其中database参数设置为MyProdDBMyTestDB

<connectionStrings>
    <add name="MyDB" connectionString="Host=localhost;user id=myUser;password=myPassword;database=MyProdDB" providerName="Npgsql" />
</connectionStrings>

当我运行应用程序并运行测试时,我为每种类型的数据库获取了正确的连接字符串。 但是当我运行测试时出现错误: 42P01: relation "dbo.Tags" does not exist。一条简单的消息,说我没有将我的数据迁移到我的测试数据库中。

但是如何将其迁移到测试数据库?

我尝试在Package manager Console中选择测试项目,并运行以下命令:

PM> Add-Migration "Init"
No migrations configuration type was found in the assembly 'MyApp.Database.Test'. (In Visual Studio you can use the Enable-Migrations command from Package Manager Console to add a migrations configuration).

PM> Update-Database
Specify the '-Verbose' flag to view the SQL statements being applied to the target database.
No migrations configuration type was found in the assembly 'MyApp.Database.Test'. (In Visual Studio you can use the Enable-Migrations command from Package Manager Console to add a migrations configuration).

PM> Enable-Migrations
No context type was found in the assembly 'MyApp.Database.Test'.

我是否需要为DbContext指定我自己的MyApp.Database.Test课程,该课程几乎是MyApp.Database的副本?

1 个答案:

答案 0 :(得分:0)

如果您不需要DEV环境中的数据,只需删除数据库即可。您使用CreateDatabaseIfNotExists,因此它将使用最新架构创建新数据库。 更重要的是,您可以在配置文件中配置初始化程序。在PROD上使用CreateDatabaseIfNotExists inializer,在DEV上使用DropCreateDatabaseIfModelChanges。因此,如果模型将发生变化,您将不得不在PROD上使用迁移,但DEV将只删除数据库并再次创建。

示例:

<contexts>      
  <context type="Elmah.SqlServer.EFInitializer.ElmahContext, Elmah.SqlServer.EFInitializer">
    <databaseInitializer type="Elmah.SqlServer.EFInitializer.ElmahDatabaseInitializer, Elmah.SqlServer.EFInitializer" />
  </context>      
</contexts>

或查看here

相关问题