0

I can't figure out how to handle connection strings in EF and NetCore

I have a solution with EntityFrameworkCore 3.1.7 and two projects:

WebApp.csproj
ShraedLibrary.csproj
   - appsettings.json

All data connection stuffs are in ShraedLibrary, where I have this constructors:

public DatabaseContext (DbContextOptions<DatabaseContext> options, ILoggerProvider loggerProvider)

This works fine, but I cannot Update-Database using the connection string from appsettings.json because there is no parameterless constructor.

When I hardcode the connection string inside a parameterless constructor then it works

What is the right way of doing this?

[EDIT]

Don't use -Project in Update-Database solved the problem.

1 Answer 1

1

Presumably, you need to create IDesignTimeDbContextFactory<TContext>.

EntityFramework Core migrations works by running your code, if that isn't possible (as it is your case with the shared library), then you need to provide more information about how your DbContext could be created. For that purpose you can use this IDesignTimeDbContextFactory<TContext> factory.

Sign up to request clarification or add additional context in comments.

5 Comments

Why can't my code be run? what is the difference for it to be in a library? - I will check the IDesignTimeDbContextFactory<TContext> now. Thanks! :)
Your library doesn't have access to the startup of you app, where you have configured the DbContext (in the ConfigureServices(...) method). So, it doesn't know from where to get the connection string.
why it cannot? Should't it work if I do Update-Database -StartupProject WebApp -Project SharedLibrary ?
How have you configured EF in the services? Can you try using CLI, not PMC. Also, what error it gives you?
I figured out, you don't need to do -Project but only -StartupProject. Your answer pointed me in the right direction, Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.