2016-06-28 83 views
0

我有一个测试dbcontext,我用它进行集成测试,它有未决的更改。这是在这个项目中:app.WebApi.Integration实体框架代码优先 - 更新不同项目中的数据库

using System.Data.Entity; 
using System.Data.Entity.Infrastructure; 
using app.Web.Data; 
using app.Web.Model.Entities; 

namespace app.WebApi.Integration.Data 
{ 
    public class IntegrationTestDbContext : DbContext, IDbContextFactory<IntegrationTestDbContext> 
    { 
     public IntegrationTestDbContext(string conn = "DefaultConnection") 
      : base(conn) 
     { 
      Configuration.LazyLoadingEnabled = false; 
     } 

     public IntegrationTestDbContext() { } 

     public virtual IDbSet<Question> Questions { get; set; } 
     public virtual IDbSet<Answer> Answers { get; set; } 


     public virtual void MarkAs(object item, EntityState entityState) 
     { 
      Entry(item).State = entityState; 
     } 

     public IntegrationTestDbContext Create() 
     { 
      return new IntegrationTestDbContext(); 
     } 
    } 
} 

但我的迁移是在一个单独的项目:app.Web.Data。有谁知道ef命令,我可以通过其他项目的迁移更新IntegrationTestDbContext?

+0

难道我已了解正确的呢?其他项目中的迁移历史记录(迁移文件),并且您有两个用于生产和一个用于测试的数据库上下文? –

+0

@BassamAlugili目前我们有两个单独的数据库上下文指向相同的SQL服务器数据库。其中一个数据库上下文被我们的集成测试使用,并且仅在这个项目中出于这个原因。如果我尝试更新集成上下文的迁移,它说有未决的更改。我想知道是否可以使用另一个程序集中的迁移类。 –

回答

-1

这是我使用的.NET核心的命令(.NET 5)

dnx ef migrations add ClassLibraryMigration -c ClassLibraryContext -p ClassLibrary 

dnx ef database update -c ClassLibaryContext 
+0

他的问题与点网核心没有关系,而在网点核心发布candate 2 dnx已经过时。 –

+0

解决方案是在.net 4.6中,所以这个答案不适用于我。 –

0

你需要一个定制DbMigrationsConfiguration:

namespace MyProgram.Migrations 
{ 
    using System; 
    using System.Data.Entity; 
    using System.Data.Entity.Migrations; 
    using System.Linq; 
    using System.Reflection; 
    using MyProgram; 

    internal sealed class MyConfiguration : DbMigrationsConfiguration<MyProgram.MyDbContext> 
    { 
     public Configuration() 
     { 
      AutomaticMigrationsEnabled = false; 

      // This is the assembly where your real migration are (Your DbContext not for test!) 
      MigrationsAssembly = Assembly.GetExecutingAssembly(); 
      MigrationsNamespace = "AssemblyNamespace.Migrations"; 
     } 
    } 
} 

那之后,你可以从代码中创建的迁移通过使用DbMigrator或使用类似的NuGet控制台:

更新数据库[-SourceMigration] [-TargetMigration] [-Script] [-Force] [-ProjectName ] [-StartUpProjectName] [-ConfigurationTypeName] [-ConnectionStringName] []

更新数据库将创建和更新使用的数据库。

Update-Database -TargetMigration YourId -ProjectName MyProject -ConfigurationTypeName MyProject.Migrations.MyConfiguration 

您可以通过连接字符串参数更新数据库命令,如果启动项目(app.config)中不包含连接字符串