❔ 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
If it was called on
services
, call it on application.Services
, IIRCThis is a screenshot of how it was done in .NET 6
This is it in .NET 7, I'm not sure where the method should be called
Just add it somewhere after
builder.Services.AddDbContext()
thenSorry if I'm being slow but do I need to put something before application.Services.[...]?
This code
Sorry again I don't quite follow, I assume it's not meant to be like this?
Remove that
app.Services....?
line
See what the error is with ApplicationDbContext
CS7036: There is no argument given that corresponds to the required parameter 'opts' of 'ApplicationDbContext.ApplicationDbContext(DbContextOptions<ApplicationDbContext>)'
ApplicationDbContext.cs
Ah
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<
Try this to get the dbcontext
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
That code works for both .net 6 and .net 7 tho
I’ll give it another try
I tried adding this code and I'm not sure how to resolve the issue
dbcontexts need to be instantiated within a scope
.
You are a saint
Thank you so much
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.