实体框架代码首先在不同的项目中更新数据库
本文关键字:项目 更新 数据库 代码 框架 实体 | 更新日期: 2023-09-27 17:51:26
我有一个用于集成测试的测试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与其他项目的迁移?
您需要自定义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控制台从代码中创建迁移:
Update-Database [- sourcemmigration] [-TargetMigration] [-Script] [-Force] [-ProjectName] [-StartUpProjectName] [-ConfigurationTypeName] [-ConnectionStringName] []
update - database将创建并更新使用的数据库。
Update-Database -TargetMigration YourId -ProjectName MyProject -ConfigurationTypeName MyProject.Migrations.MyConfiguration
如果启动项目(app.config)不包含连接字符串
这是我用于。net core(。net 5)的命令
dnx ef migrations add ClassLibraryMigration -c ClassLibraryContext -p ClassLibrary
dnx ef database update -c ClassLibaryContext