EF Core - automatically create DbContext class - c#

Is there any CLI command or Visual Studio extension to create ApplicationDBContext class automatically from Models folder where my model classes are located: 'User', 'Product', 'Account'?
Result of the CLI command or extension should be:

Related

.Net 6 EF Core DbContext and Models In Separate Class Libary

I have a solution with the following projects:
ASP.NET Core MVC website
ASP.NET Core Web API
DAL [incl DbContext and model classes]
Both the website and API reference the DAL and can use it's dbContext and model classes.
Both these projects have an appsettings.json file with the connection string and DB access is all working.
I can't how ever work out how to add migrations.
If I set the default project to the DAL project, I get this error:
Unable to create an object of type 'myDbContext'. For the different patterns supported at design time, see https://go.microsoft.com/fwlink/?linkid=851728
If I set it to the Api or website, I get:
Your target project 'website' doesn't match your migrations assembly 'DAL'. 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("website")). 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 can find information on how to set up a separate class lib for the dbcontect and models for .NET Core 3.1 but I am struggling with .NET 6.
I have tried to follow this tutorial
https://garywoodfine.com/using-ef-core-in-a-separate-class-library-project/
But it's not the same as .net 6 so I cant follow it as I get errors when I try and create the DBContextFactory towards the bottom. The SetBasePath is not a definition within ConfigurationBuilder. I'm not fluent enough with .NET Core to work out whats required.
I have the exact same setup as you have with a website, api and a DAL layer.
This is how I register the DbContext in the website and in the api program.cs:
builder.Services.AddDbContext<AppDbContext>(
options => options.UseSqlServer(config.ConnectionString, sqlOptions => {
sqlOptions.MigrationsAssembly("App.Entities");}));
This is how the AppDbContext is created in the DAL project:
public class AppDbContext : DbContext
{
public AppDbContext(DbContextOptions<AppDbContext> options) : base(options)
{ }
// Your DbSet entities here
}
Then when you run your first migration command "Add-Migration" you need to select the DAL project in the package manager console dropdown and it should automatically create the migration folder with the migration files.
You need to have the following packages installed in the DAL project:
Microsoft.EntityFrameworkCore.SqlServer
Microsoft.EntityFrameworkCore.Tools
Honestly, one would need more information to narrow down the problem.
I think there are two possible problems.
You are not using the exact DB Context in the program.cs of the two project in the presentation layer(MVC and API).
You have updated the migration the migration on API or MVC, or you have made changes to the database hence the comparison is not as clear.
How to resolve:
Make sure that database connection string in the two application.json
is same
Make sure that in the Program.cs of the the API and the MVC, that you have added the exact dbcontext from DAL "and is identical".
Make sure you have uniform Nugget package across the solution for the EF tool, Server, Design
Make sure the Models in the last migration mirrors what is obtainable in the database.
Make sure that the Package Manager console is has DAL selected as the default project, while the startup project which can be MVC or API is not having any errors.
Make sure that there is a dbSet<> in the dbContext in DAL before adding a migration

dotnet ef dbcontext scaffold does not run correctly from code

I am trying to create a model from an existing database from c# code.
The statements I use are exactly the ones given in the Microsoft documentation at https://learn.microsoft.com/en-us/ef/core/get-started/overview/first-app?tabs=netcore-cli
and I am simply executing them via a process created in c# code.
When executed directly from the command line the entity model is generated correctly for both the db context and the classes for the entities.
When executed via a process from VS2022 the statements run correctly without reporting an error but only the db context is generated, and no classes for the entities are created.
If you run in an empty folder the statements as generated by the code, ie:
dotnet new console
dotnet add package Microsoft.EntityFrameworkCore.SqlServer
dotnet add package Microsoft.EntityFrameworkCore.Design
dotnet ef dbcontext scaffold "Server=***.***.***.***;User Id=******;Password=*********" Microsoft.EntityFrameworkCore.SqlServer -o Model -f -v
and examini the result folder, in the Model folder you will find the dbcontext AND all the entities definitions for the database.
I am confused at this point, and would like to hear from anybody who might have an idea of what is happening.

How can I create the database entities in a layered application

I have to create a layered .net core application including a database. I want to build the database entities with sql-first approach. The solution looks like this:
All of the projects are class libaries, except the FoodSupplementCompany.Program.
My question is, how can I use Scaffold-DbContext to generate the entities to the FoodSupplementCompany.Data project?
You can use the Package Manager Console:
cd .\FoodSupplementCompany.Data
dotnet ef dbcontext scaffold -s ..\FoodSupplementCompany.Program
The line cd .\FoodSupplementCompany.Data is for navigating into project directory where the DBContext is located.
And the line -s ..\FoodSupplementCompany.Program is for stating where is the startup project to use.
As the guide here states: scaffold-dbcontext
Example:
Scaffold-DbContext
"Server=(localdb)\mssqllocaldb;Database=Blogging;Trusted_Connection=True;"
Microsoft.EntityFrameworkCore.SqlServer
-OutputDir Models
-OutputDir -> The directory to put files in. Paths are relative to the project directory.

Cannot see the DbContext from another project in asp.net core

I have a web api project "Reactivities" and another project "Persisitence" to place my DbContext. When I try to use my add-migration in the Reactivities, using this syntax in the console add-migration InitalCreate -Context .\Persistence I get this error:
No DbContext named '.\Persistence' was found.
Even if I use add-migration InitialCreate -Context .\Persistence\DataContext still I get the same error,
This is in my startup class in Reactivities
services.AddDbContext<DataContext>(opt =>
{
opt.UseSqlite(Configuration.GetConnectionString("DefaultConnection"));
});
How can I correct this?
You have to do migration work in a project that instantiates the dbcontext, in my case I have created a dbmigrator project with a class that inherits the
IDesignTimeDbContextFactory<T>
where T is the dbcontext type.
This allows me to have a project that has the dbcontexts, a project that works with migrations and a project that uses the dbcontexts independently of each other.
This guide shows you how to use the interface i mentioned:
https://codingblast.com/entityframework-core-idesigntimedbcontextfactory/

Issue in Entity Framework Core

I'm new to EF Core and I have a problem in this section (Startup.cs):
services.AddDbContext<DataContext>(opt =>
{
opt.UseSqlite(Configuration.GetConnectionString("DefaultConnection"));
});
The DataContext is a .cs file, in the Persistence folder, and it's a class that derives from DbContext.
When I write in above of Startup.cs:
using Persistnece;
using Microsoft.EntityFramewormCore;
Visual Studio Code throws an error :
Remove unnecessary using !?
and when I use
dotnet ef migration add InitialCreate -p Persistence/ -s API/
command, the result is
Build start .. Build failed
What is the problem?
Note: I have downloaded Microsoft.EntityFrameworkCore and Microsoft.EntityFrameworkCore.sqlite
See the error that appears in the screenshot:

Categories