使用不同的程序集添加迁移

我正在做一个 ASP.NET CORE1.0.0的项目,我正在使用 EntityFrameworkCore。我有单独的程序集,我的项目结构如下:

ProjectSolution
-src
-1 Domain
-Project.Data
-2 Api
-Project.Api

在我的 Project.ApiStartup

public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<ProjectDbContext>();


services.AddIdentity<IdentityUser, IdentityRole>()
.AddEntityFrameworkStores<ProjectDbContext>()
.AddDefaultTokenProviders();
}

DbContext在我的 Project.Data项目中

public class ProjectDbContext : IdentityDbContext<IdentityUser>
{
public ProjectDbContext(DbContextOptions<ProjectDbContext> options) : base(options)
{


}


protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{


var builder = new ConfigurationBuilder();
builder.SetBasePath(Directory.GetCurrentDirectory());
builder.AddJsonFile("appsettings.json");
IConfiguration Configuration = builder.Build();


optionsBuilder.UseSqlServer(
Configuration.GetConnectionString("DefaultConnection"));
base.OnConfiguring(optionsBuilder);
}
}

当我尝试进行初始迁移时,我得到这个错误:

”你的目标项目‘ Project。Api’与您的迁移程序集‘ Project 不匹配。百科。要么更改目标项目,要么更改迁移程序集。 使用 DbContextOptionsBuilder 更改迁移程序集。例如选项。UseSqlServer (connect,b = > b. MigationsAssembly (“ Project。阿比”)。默认情况下,迁移程序集是包含 DbContext 的程序集。 通过使用 Package Manager Console 的 Default project 下拉列表,或者从包含迁移项目的目录中执行“ dotnet ef”,将目标项目更改为迁移项目

看到这个错误之后,我尝试执行位于 Project.Api中的这个命令:

Dotnet ef —— start-Project. ./Project. Api —— Assembly“ . ./. ./1 Data/Project. Data”迁移添加 Initial

我得到了这个错误:

“选项‘ Assembly’的意外值‘ . ./. ./1 Domain/Project. Data’”

我不知道为什么会出现这个错误,当我尝试使用’-Assembly’参数执行命令时。

我无法从其他程序集创建初始迁移,我搜索了有关它的信息,但没有得到任何结果。

有人有类似的问题吗?

113643 次浏览

All EF commands have this check:

if (targetAssembly != migrationsAssembly)
throw MigrationsAssemblyMismatchError;

targetAssembly = the target project you are operating on. On the command line, it is the project in the current working directory. In Package Manager Console, it is whatever project is selected in the drop down box on the top right of that window pane.

migrationsAssembly = assembly containing code for migrations. This is configurable. By default, this will be the assembly containing the DbContext, in your case, Project.Data.dll. As the error message suggests, you have have a two options to resolve this

1 - Change target assembly.

cd Project.Data/
dotnet ef --startup-project ../Project.Api/ migrations add Initial


// code doesn't use .MigrationsAssembly...just rely on the default
options.UseSqlServer(connection)

2 - Change the migrations assembly.

cd Project.Api/
dotnet ef migrations add Initial


// change the default migrations assembly
options.UseSqlServer(connection, b => b.MigrationsAssembly("Project.Api"))

I ran on the same problem and found this

We’re you trying to run your migrations on a class library? So was I. Turns out this isn’t supported yet, so we’ll need to work around it.

EDIT: I found solution on this git repo

Currently I think EF only supports to add migrations on projects not yet on class libraries.

And just side note for anybody else who wants to add migrations to specific folder inside your project:

EF CLI not support this yet. I tried --data-dir but it didn't work.

The only thing works is to use Package Manager Console:

  1. Pick your default project
  2. use -OutputDir command parameter, .e.g., Add-Migration InitConfigurationStore -OutputDir PersistedStores/ConfigurationStore command will output the mgiration to the folder 'PersistedStores/ConfigurationStore' in my project.

Updates as of 10/12/2017

public void ConfigureServices(IServiceCollection services)
{
...
    

string dbConnectionString = services.GetConnectionString("YOUR_PROJECT_CONNECTION");
string assemblyName = typeof(ProjectDbContext).Namespace;


services.AddDbContext<ProjectDbContext>(options =>
options.UseSqlServer(dbConnectionString,
optionsBuilder =>
optionsBuilder.MigrationsAssembly(assemblyName)
)
);


...
}

Updates as of 1/4/2021

I am using EF Core 5.0 this time. I was hoping optionBuilder.MigrationAssembly() method would work when you want to generate migrations under a folder in the target project but it didn't.

The structure I have this time is:

src
- presentation
- WebUI
- boundedContext
- domain
- application
- infrastructure
- data/
- appDbContext
- email-services
- sms-services

See I have the infrastructure as a class library, and it contains multiple folders because I want to just have a single project to contain all infrastructure related services. Yet I would like to use folders to organize them.

string assemblyName = typeof(ProjectDbContext).Namespace would give me the correct path "src/infrastructure/data", but doing add-migration still fails because that folder is not an assembly!

Could not load file or assembly. The system cannot find the file specified.

So the only thing that actually works is, again, to specify the output folder...

Using .NET Core CLI you would have to open the command line under your target project, and do the following:

dotnet ef migrations add Init
-o Data\Migrations
-s RELATIVE_PATH_TO_STARTUP_PROJECT

I had the same problem until I noticed that on the package manager console top bar => "Default Projects" was supposed to be "Project.Data" and not "Project.API".

Once you target the "Project.Data" from the dropdown list and run the migration you should be fine.

default project selection

Using EF Core 2, you can easily separate your Web project from your Data (DbContext) project. In fact, you just need to implement the IDesignTimeDbContextFactory interface. According to Microsoft docs, IDesignTimeDbContextFactory is:

A factory for creating derived DbContext instances. Implement this interface to enable design-time services for context types that do not have a public default constructor. At design-time, derived DbContext instances can be created in order to enable specific design-time experiences such as Migrations. Design-time services will automatically discover implementations of this interface that are in the startup assembly or the same assembly as the derived context.

In the bottom code snippet you can see my implementation of DbContextFactory which is defined inside my Data project:

public class DbContextFactory : IDesignTimeDbContextFactory<KuchidDbContext>
{
public KuchidDbContext CreateDbContext(string[] args)
{
var configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json")
.Build();


var dbContextBuilder = new DbContextOptionsBuilder<KuchidDbContext>();


var connectionString = configuration.GetConnectionString("Kuchid");


dbContextBuilder.UseSqlServer(connectionString);


return new KuchidDbContext(dbContextBuilder.Options);
}
}

Now, I can initialize EF migration by setting my Web project as the StartUp project and selecting my Data project inside the Package Manager Console.

Add-Migration initial

You can find more details here. However, this blog post uses an obsoleted class instead of IDesignTimeDbContextFactory.

For all of you who have multiple startup projects.

Notice that you need to set your target project as startup project - Project.Api(form the question example) should be the startup project.

Hope that will help someone :)

I was facing similar issue, though answers seems straight forward somehow they didn't work. My Answer is similar to @Ehsan Mirsaeedi, with small change in DbContextFactory class. Instead of Adding migration assembly name in Startup class of API, I have mentioned in DbContextFactory class which is part of Data project(class library).

public class DbContextFactory : IDesignTimeDbContextFactory<KuchidDbContext>
{
public KuchidDbContext CreateDbContext(string[] args)
{
var configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json")
.Build();


var dbContextBuilder = new DbContextOptionsBuilder<KuchidDbContext>();


var connectionString = configuration.GetConnectionString("connectionString");


var migrationAssemblyName= configuration.GetConnectionString("migrationAssemblyName");


dbContextBuilder.UseSqlServer(connectionString, o => o.MigrationAssembly(migrationAssemblyName));


return new KuchidDbContext(dbContextBuilder.Options);
}
}

You would need 'Microsoft.Extensions.Configuration' and 'Microsoft.Extensions.Configuration.Json' for SetBasePath & AddJsonFile extensions to work.

Note: I feel this is just a work around. It should pickup the DbContextOptions from the startup class somehow it is not. I guess there is definitely some wiring issue.

(ASP.NET Core 2+)

Had the same issue. Here is what I did:

  1. Reference the project that contains the DbContext (Project.A) from the project that will contain the migrations (Project.B).

  2. Move the existing migrations from Project.A to Project.B (If you don't have migrations - create them first)

  3. Configure the migrations assembly inside Project.A

options.UseSqlServer( connectionString, x => x.MigrationsAssembly("Project.B"));

Assuming your projects reside in the same parent folder:

  1. dotnet ef migrations add Init --p Project.B -c DbContext

The migrations now go to Project.B

Source: Microsoft

There are multiple projects included in the Solution.

Solution
|- MyApp (Startup Proj)
|- MyApp.Migrations (ClassLibrary)

Add-Migration NewMigration -Project MyApp.Migrations

Note: MyApp.Migrations also includes the DbContext.

Add Migration With CLI Command:

dotnet ef migrations add NewMigration --project YourAssemblyName

Add Migration With PMC Command:

Add-Migration NewMigration -Project YourAssemblyName

Link About CLI Commands

Link About PMC Commands

I have resolved it by adding below line in Startup.cs. Hope it will help you also. I have used Postgres you can use Sql Server instead of that

     var migrationsAssembly = typeof(Startup).GetTypeInfo().Assembly.GetName().Name;
services.AddIdentityServer(options =>
{
options.Events.RaiseErrorEvents = true;
options.Events.RaiseInformationEvents = true;
options.Events.RaiseFailureEvents = true;
options.Events.RaiseSuccessEvents = true;


})
.AddSigningCredential(cert)
.AddCustomUserStore<IdentityServerConfigurationDbContext>()
// this adds the config data from DB (clients, resources)
.AddConfigurationStore(options =>
{
options.ConfigureDbContext = builder =>
builder.UseNpgsql(connectionString,
sql => sql.MigrationsAssembly(migrationsAssembly));
})
// this adds the operational data from DB (codes, tokens, consents)
.AddOperationalStore(options =>
{
options.ConfigureDbContext = builder =>
builder.UseNpgsql(connectionString,
sql => sql.MigrationsAssembly(migrationsAssembly));


// this enables automatic token cleanup. this is optional.
options.EnableTokenCleanup = true;
options.TokenCleanupInterval = 30;
});

The below command did the trick for me. I'm using VS Code and I run the following command:

SocialApp.Models> dotnet ef migrations add InitialMigartion --startup-project ../SocialApp.API

Courtesy: https://github.com/bricelam/Sample-SplitMigrations

This is for EF Core 3.x.

Based on this answer from Ehsan Mirsaeedi and this comment from Ales Potocnik Hahonina, I managed to make Add-Migration work too.

I use Identity Server 4 as a NuGet package and it has two DB contexts in the package. Here is the code for the class that implements the IDesignTimeDbContextFactory interface:

public class PersistedGrantDbContextFactory : IDesignTimeDbContextFactory<PersistedGrantDbContext>
{
public PersistedGrantDbContext CreateDbContext(string[] args)
{
var configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json")
.Build();


var dbContextBuilder = new DbContextOptionsBuilder<PersistedGrantDbContext>();


var connectionString = configuration.GetConnectionString("db");


dbContextBuilder.UseSqlServer(connectionString, b => b.MigrationsAssembly("DataSeeder"));


return new PersistedGrantDbContext(dbContextBuilder.Options, new OperationalStoreOptions() { ConfigureDbContext = b => b.UseSqlServer(connectionString) });
}
}

Compared to the answer of Ehsan Mirsaeedi I modified these: I added the MigrationsAssembly:

dbContextBuilder.UseSqlServer(connectionString, b => b.MigrationsAssembly("DataSeeder"));

Where the "DataSeeder" is the name of my startup project for seeding and for migrations.

I added an options object with ConfigureDbContext property set to the connection string:

return new PersistedGrantDbContext(dbContextBuilder.Options, new OperationalStoreOptions() { ConfigureDbContext = b => b.UseSqlServer(connectionString) });

It is now usable like this: 'Add-Migration -Context PersistedGrantDbContext

At this point, when a migration has been created, one can create a service for this in a migration project having a method like this:

public async Task DoFullMigrationAsync()
{
using (var scope = _serviceProvider.GetRequiredService<IServiceScopeFactory>().CreateScope())
{
var persistedGrantDbContextFactory = new PersistedGrantDbContextFactory();


PersistedGrantDbContext persistedGrantDbContext = persistedGrantDbContextFactory.CreateDbContext(null);
await persistedGrantDbContext.Database.MigrateAsync();


// Additional migrations
...
}
}

I hope I helped someone.

Cheers,

Tom

All you have to do, is modify your ConfigureServices like this:

    public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<ProjectDbContext>(item => item.UseSqlServer(
Configuration.GetConnectionString("DefaultConnection"),
b => b.MigrationsAssembly("Project.Api")));


services.AddIdentity<IdentityUser, IdentityRole>()
.AddEntityFrameworkStores<ProjectDbContext>()
.AddDefaultTokenProviders();
}

By Default VS will use the Assembly of the project where the DbContext is stored. The above change, just tells VS to use the assembly of your API project.

You will still need to set your API project as the default startup project, by right clicking it in the solution explorer and selecting Set as Startup Project

dotnet ef update-database --startup-project Web --project Data

  1. Web is my startup project
  2. Data is my the my class library

Mine is a single .net core web project.

Had to ensure 1 thing to resolve this error. The following class must be present in the project.

public class SqlServerContextFactory : IDesignTimeDbContextFactory<SqlServerContext>
{
public SqlServerContext CreateDbContext(string[] args)
{


var currentEnv = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");


var configuration = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json")
.AddJsonFile($"appsettings.{ currentEnv ?? "Production"}.json", optional: true)
.Build();


var connectionString = configuration.GetConnectionString("MsSqlServerDb");


var optionsBuilder = new DbContextOptionsBuilder<SqlServerContext>();
//var migrationAssembly = typeof(SqlServerContext).Assembly.FullName;
var migrationAssembly = this.GetType().Assembly.FullName;


if (connectionString == null)
throw new InvalidOperationException("Set the EF_CONNECTIONSTRING environment variable to a valid SQL Server connection string. E.g. SET EF_CONNECTIONSTRING=Server=localhost;Database=Elsa;User=sa;Password=Secret_password123!;");


optionsBuilder.UseSqlServer(
connectionString,
x => x.MigrationsAssembly(migrationAssembly)
);


return new SqlServerContext(optionsBuilder.Options);
}
}

Note there the migration assembly name.

//var migrationAssembly = typeof(SqlServerContext).Assembly.FullName;

I have commented that out. That is the culprit in my case. What is needed is the following.

var migrationAssembly = this.GetType().Assembly.FullName;

With that in place the following two commands worked perfectly well.

Add-Migration -StartupProject MxWork.Elsa.WebSqLite -Context "SqlServerContext" InitialMigration
Add-Migration InitialMigration -o SqlServerMigrations -Context SqlServerContext

If you want a reference of such a project, take a look at this git hub link

There you should find a project attached with the name Elsa.Guides.Dashboard.WebApp50.zip. Download that see that web app.

Directory Structure

Root
APIProject
InfrastructureProject

By going Root directory To add migration

dotnet ef migrations add Init --project InfrastructureProject -s APIProject

To update database

dotnet ef database update --project InfrastructureProject -s APIProject

If you have solution with few projects, where

  • API - startup here
  • EF - db context here

then to perform migration:

  1. install Microsoft.EntityFrameworkCore.Tools for API
  2. open Package Manager Console in Visual Studio
  3. perform Add-Migration InitialCreate

notice that "DefaultProject: EF" should be selected in the console.