I am new to Ef Core. Trying to seed data while migration update.
He is how i did it
First created an initializer class:
using AcademicNet.Data.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AcademicNet.Data
{
public class PersonInitializer
{
private AcademicPortalContext _context;
public PersonInitializer(AcademicPortalContext context)
{
_context = context;
}
public async Task Seed()
{
if(!_context.PersonCategoryStatuses.Any())
{
_context.AddRange(_personCategoryStatus);
await _context.SaveChangesAsync();
}
if (!_context.PersonCategories.Any())
{
_context.AddRange(_personCategory);
await _context.SaveChangesAsync();
}
if (!_context.People.Any())
{
_context.AddRange(_people);
await _context.SaveChangesAsync();
}
}
List<PersonCategory> _personCategory = new List<PersonCategory>
{
new PersonCategory()
{
Name = "Internal Person Category",
Description = "Silahkan diganti redaksi ini",
PersonCategoryStatusId = 2,
StartDate = DateTime.UtcNow,
ModifiedDate = DateTime.UtcNow
}
};
List<Person> _people = new List<Person>
{
new Person()
{
FirstName = "Jannen",
LastName = "Siahaan",
Email = "j.siahaan@any.com",
DateAdd = DateTime.UtcNow,
ModifiedDate = DateTime.UtcNow
}
};
List<PersonCategoryStatus> _personCategoryStatus = new List<PersonCategoryStatus>
{
new PersonCategoryStatus()
{
Status = "Baru"
},
new PersonCategoryStatus()
{
Status = "Valid"
},
new PersonCategoryStatus()
{
Status = "Expired"
}
};
}
}
2. At the ConfigurationServices in Startup.cs add this:
services.AddTransient<PersonInitializer>();
- At the parameter of Configure method at the Startup.cs add this injection:
public void Configure(IApplicationBuilder app,
IHostingEnvironment env,
ILoggerFactory loggerFactory,
PersonInitializer personSeeder,
AcademicPortalIdentityInitializer identitySeeder)
4. At the end of this "public void Configure" after app.UseMvc()
personSeeder.Seed().Wait();
suppose i have run the migration
and want to add a new PersonCategoryStatus as 'inValid' later. How can i acheive this.
new PersonCategoryStatus
List<PersonCategoryStatus> _personCategoryStatus = new List<PersonCategoryStatus>
{
new PersonCategoryStatus()
{
Status = "Baru"
},
new PersonCategoryStatus()
{
Status = "Valid"
},
new PersonCategoryStatus()
{
Status = "Expired"
},
new PersonCategoryStatus()
{
Status = "Invalid"
}
};
Any help is much appreciated. Thanks in advance