我有一个测试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 :(得分:1)
您需要自定义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将创建和更新使用过的数据库。
Update-Database -TargetMigration YourId -ProjectName MyProject -ConfigurationTypeName MyProject.Migrations.MyConfiguration
如果启动项目(app.config)不包含连接字符串,则可以将连接字符串作为update-database命令的参数传递
答案 1 :(得分:-1)
这是我用于.net core(.net 5)
的命令dnx ef migrations add ClassLibraryMigration -c ClassLibraryContext -p ClassLibrary
dnx ef database update -c ClassLibaryContext