C
C#2mo ago
morry329#

Does it make sense to two references (to database migration and data seeding) in the same using

I am totally new to this, so I rely on chatGPT a lot With the help of GPT I have wrote a code like this
var app = builder.Build();

using (var scope = app.Services.CreateScope())
{
var db = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
db.Database.Migrate();
var services = scope.ServiceProvider;

var seeder = new DataSeed(db);
seeder.SeedModels();
}
var app = builder.Build();

using (var scope = app.Services.CreateScope())
{
var db = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
db.Database.Migrate();
var services = scope.ServiceProvider;

var seeder = new DataSeed(db);
seeder.SeedModels();
}
As you see this is the Program.cs snippet (ASP.NET Core 7). My concern is that this code might make no sense to have db.Database.Migrate(); and seeder.SeedModels(); under the same roof (the same using). I don't know much about all this ASP.NET world but I migrated database a couple of times via the commandline like dotnet ef add-migration etc. so I started wondering if db.Database.Migrate(); in Program.cs makes any sense.
What do you all think of this snippet?
2 Replies
Jimmacle
Jimmacle2mo ago
the only thing i find odd about this code is this line which doesn't do anything var services = scope.ServiceProvider; you need the rest of the code inside the using because it presumably does something with the ApplicationDbContext whose lifetime is controlled by the service scope if you put it outside the using, then the scope would be disposed which would dispose the dbcontext and cause runtime errors when you try to seed migrating the database at runtime can make sense, that really depends on your deployment process
morry329#
morry329#2mo ago
Thank you so much for the detailed explanation 🙏 I will remove the services line then
Want results from more Discord servers?
Add your server