❔ Entity Framework 7 - Where to call EnsureCreared method

I'm trying to create a PGSQL database with a code-first approach using EF7 in my ASP.NET Core Web API application. I have created the models, the ApplicationDbContext and the connection string, and want to know how to call the EnsureCreated method rather than using a migration to an existing database. Previously in .NET 6, it was called in the ConfigurationServices method in the Startup.cs file, but I'm struggling to find how top do the equivalent in Program.cs, which Startup.cs has been integrated into as part of .NET 7. Thanks in advance!
22 Replies
Angius
Angius2y ago
If it was called on services, call it on application.Services, IIRC
TotallyJustin
TotallyJustinOP2y ago
This is a screenshot of how it was done in .NET 6
TotallyJustin
TotallyJustinOP2y ago
This is it in .NET 7, I'm not sure where the method should be called
Angius
Angius2y ago
Just add it somewhere after builder.Services.AddDbContext() then
TotallyJustin
TotallyJustinOP2y ago
Sorry if I'm being slow but do I need to put something before application.Services.[...]?
Angius
Angius2y ago
Angius
Angius2y ago
This code
TotallyJustin
TotallyJustinOP2y ago
Sorry again I don't quite follow, I assume it's not meant to be like this?
Angius
Angius2y ago
Remove that app.Services....? line See what the error is with ApplicationDbContext
TotallyJustin
TotallyJustinOP2y ago
CS7036: There is no argument given that corresponds to the required parameter 'opts' of 'ApplicationDbContext.ApplicationDbContext(DbContextOptions<ApplicationDbContext>)'
TotallyJustin
TotallyJustinOP2y ago
ApplicationDbContext.cs
Angius
Angius2y ago
Ah
Angius
Angius2y ago
Stack Overflow
How do you do database.ensurecreated() in aspnet core web applicati...
In a .NET 5 web application, we use code such as the following in startup.cs to initialize the DB using Entity Framework: using (var serviceScope = app.ApplicationServices.GetService<
Angius
Angius2y ago
Try this to get the dbcontext
TotallyJustin
TotallyJustinOP2y ago
Already looked at that, it has the same issue of being for .NET 6. I’ve used EF 7 before just not by using the EnsureCreated method and instead using migrations
Monsieur Wholesome
That code works for both .net 6 and .net 7 tho
TotallyJustin
TotallyJustinOP2y ago
I’ll give it another try
TotallyJustin
TotallyJustinOP2y ago
I tried adding this code and I'm not sure how to resolve the issue
Monsieur Wholesome
dbcontexts need to be instantiated within a scope .
TotallyJustin
TotallyJustinOP2y ago
You are a saint Thank you so much
Accord
Accord2y ago
Was this issue resolved? If so, run /close - otherwise I will mark this as stale and this post will be archived until there is new activity.
Want results from more Discord servers?
Add your server