DiPix
DiPix

Reputation: 6083

Asp.net core + EF Code first, migration files in different project

In my solution I want to use Asp.net core + EF Code first

I have 2 projects:

In CC.API I have startup class and there is:

services.AddDbContext<DataContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"), b => b.MigrationsAssembly("CC.Infrastructure")));

(Connection string is in appsettings.json)

As you can see I'm trying to keep migration files in different project - CC.Infrastructure.

Unfortunately whilst Add-Migration Init I receives an error: Your target project 'PK.API' doesn't match your migrations assembly 'PK.Infrastructure'. Either change your target project or change your migrations assembly

If I will change in startup b => b.MigrationsAssembly("CC.API") then everthing works fine, but files migration files will be in CC.API :/

Upvotes: 7

Views: 6998

Answers (3)

panky sharma
panky sharma

Reputation: 2189

As said by IvanZazz

  1. Set UI/Web project as startup project
  2. Set Infrastructure as default project in package manager console dropdown, select the drop-down of default project for package manager console, set it to CC.Infrastructure or the project which has DbContext class
  3. Now run this command in package manage

add-migration InitialIdentityModel

enter image description here

Upvotes: 4

Todd Skelton
Todd Skelton

Reputation: 7239

You have to add Microsoft.EntityFrameworkCore.Tools.DotNet to your CC.Infrastructure project. Right click the project and select Edit *.csproj. Then, add the following:

  <ItemGroup>
    <DotNetCliToolReference Include="Microsoft.EntityFrameworkCore.Tools.DotNet" Version="2.0.0-preview2-final" />
  </ItemGroup>

You can't add this from the Nuget package manager. It has to be added directly to the project.

Once you do that. You can run the command with the startup project set as CC.API. Go to the folder for your class library. The easiest way it to right click the project and Open Folder in File Explorer. Then, type cmd in the address bar of the File Explorer to open a command prompt in that folder.

Now use the following command to create the migration:

dotnet ef migrations add InitialCreate -c DataContext --startup-project ../CC.API/CC.API.csproj

Upvotes: 0

BradleyDotNET
BradleyDotNET

Reputation: 61369

This is/was a longstanding issue with EF Core. The solution used to be making your class library an executable (temporarily) and then run all EF operations against it.

With current tooling, you can just run Add-Migration while in the library folder; the only caveat is you need to set the startup-project flag to the actual executable's project.

So the command ends up being something like:

C:\CC.Infrastructure>dotnet ef migrations add NewMigration --startup-project ../CC.API/CC.API.csproj

Upvotes: 11

Related Questions