user15203423
user15203423

Reputation:

How to create migrations from library project by targeting a Web Api project and use the lib project as the migrations assembly?

I created a .Net 5 Web Api project and a library project. In the library project I created a database entity, a context and an extension to register the context on startup

public static IServiceCollection AddContexts(this IServiceCollection services)
    => services.AddDbContext<CarsContext>(x => x.UseNpgsql("Host=host;Database=db;Username=user;Password=pw"));

In the Web Api project I call the AddContexts method in the startup file. With the EF cli I want to generate migrations in the lib project by calling this in the Api directory

dotnet ef migrations add Init --startup-project . -o ./LibProj

The build succeeds but unfortunately I get this error

Your target project 'ApiProj' doesn't match your migrations assembly 'LibProj'. Either change your target project or change your migrations assembly. Change your migrations assembly by using DbContextOptionsBuilder. E.g. options.UseSqlServer(connection, b => b.MigrationsAssembly("ApiProj")). By default, the migrations assembly is the assembly containing the DbContext. Change your target project to the migrations project by using the Package Manager Console's Default project drop-down list, or by executing "dotnet ef" from the directory containing the migrations project.

I don't think my Api project should deal with database related things. Is there a way I can fix my command to use the Api project as the startup project but take the context from the lib project and put the migrations into the lib project?

Upvotes: 1

Views: 929

Answers (2)

Serhii
Serhii

Reputation: 753

To run this commands from your library project you can Add packages to your library project:

Microsoft.EntityFrameworkCore.Design
Microsoft.EntityFrameworkCore.SqlServer

After that you can ran ef commands from your library folder and reference it to your ApiProj. Example:

dotnet ef --startup-project ../ApiProj migrations add init
dotnet ef --startup-project ../ApiProj database update

Upvotes: 1

Matt U
Matt U

Reputation: 5118

Use the --project flag for the dotnet ef command as well:

dotnet ef migrations add Init --startup-project ./ApiProj --project ./LibProj -o ./LibProj

The --project flag sets the target project. Change the paths for each flag as needed, but I think that should give you what you need.

Upvotes: 2

Related Questions