2016-06-28 86 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)中不包含連接字符串