GSkidmore GSkidmore -4 years ago 194
ASP.NET (C#) Question

Seeding in .Net Core

I'm currently building a .NET core Identity Server application that uses migrations and wondered what the best method of seeding a database would be in regards to .NET core.

Currently I have a DbInitializer class that is called on startup (see below) but wondered if I should be doing this as a migration?

public static void Seed(IApplicationBuilder applicationBuilder)
{
ConfigurationDbContext context =
applicationBuilder.ApplicationServices.GetRequiredService<ConfigurationDbContext>();
IConfiguration oConfig =
applicationBuilder.ApplicationServices.GetRequiredService<IConfiguration>();

string sSeedingConfig = GetSeedingConfiguration(oConfig);

SeedConfigurationDb(ref context, sSeedingConfig);
}

private static void SeedConfigurationDb(ref ConfigurationDbContext oContext, string sSeedingConfig)
{
if (!oContext.ApiResources.Any())
{
var oApis = GetSeedingConfigElements(sSeedingConfig, "Apis");
List<ApiResource> lApis = null;
if (oApis != null)
{
lApis = JsonConvert.DeserializeObject<List<ApiResource>>(oApis.ToString());
}
if (lApis != null)
{
foreach (var api in lApis)
{
oContext.ApiResources.Add(api.ToEntity());
}
}
}

if (!oContext.Clients.Any())
{
var oClients = GetSeedingConfigElements(sSeedingConfig, "Clients");
List<Client> lClients = null;
if (oClients != null)
{
lClients = JsonConvert.DeserializeObject<List<Client>>(oClients.ToString());
}
if (lClients != null)
{
foreach (var client in lClients)
{
oContext.Clients.Add(client.ToEntity());
}
}
}

if (!oContext.IdentityResources.Any())
{
var oIdentityResources = GetSeedingConfigElements(sSeedingConfig, "IdentityResources");
List<IdentityResource> lIdentityResources = null;
if (oIdentityResources != null)
{
lIdentityResources = JsonConvert.DeserializeObject<List<IdentityResource>>(oIdentityResources.ToString());
}
if (lIdentityResources != null)
{
foreach (var identityresource in lIdentityResources)
{
oContext.IdentityResources.Add(identityresource.ToEntity());
}
}
}

oContext.SaveChanges();
}

Answer Source

When you enable your migrations, you get a class file named "Configuration". This class has a seed method that gets run every time you update the database trough a migration.

So you could seed your initial update trough there, and then comment it out.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download