how to seed data to database entity framework code example
Example 1: how to seed data in EF
* Seed File [0/7]
- [ ] Create Seed Project
- mkdir Seeder; cd Seeder; dotnet new console;
- [ ] Manage Dependencies
- Create Contexts
- Add in references to your DbContexts in your Seeder.csproj like
<ItemGroup>
<ProjectReference Include="..\path\name.csproj" />
</ItemGroup>
- Add needed EF packages with dotnet add package <package>
- [ ] Create Seeder Class for <ClassNameToBeSeeded>
- mkdir Models/
- nano Models/classNameSeeder.cs
(or use your ide to manage files)
- [ ] Add data to be seeded in static methods
private static IList<ClassNameToBeSeeded> SeedData()
{
IList<ClassNameToBeSeeded> pages = new List<ClassNameToBeSeeded>();
pages.Add(new ClassNameToBeSeeded
{
variable = "something",
}
);
return pages;
}
- [ ] Add in call to persist objects through context
public static void SeedToDB()
{
var contextOptions = new DbContextOptionsBuilder<ContextName>()
.UseSqlServer("ConnectionString")
.Options;
var context = new ContextName(contextOptions);
context.Database.EnsureCreated();
var sections = classNameSeeder.SeedData();
context.<contextDbSet>.AddRange(sections);
context.SaveChanges();
}
- [ ] Call this in main
namespace Seeder
{
class Program
{
public static void Main(string[] args)
{
classNameSeeder.SeedToDB();
}
}
}
- [ ] Make sure your tables are created with migrations and run the program via
dotnet run
dotnet ef database update 0 --context <context>
dotnet ef database update --context <context>
Example 2: how to seed data in EF
* Seed File [0/7]
- [ ] Create Seed Project
- mkdir Seeder; cd Seeder; dotnet new console;
- [ ] Manage Dependencies
- Add in references to your DbContexts in your Seeder.csproj like
<ItemGroup>
<ProjectReference Include="..\path\name.csproj" />
</ItemGroup>
- Add needed EF packages with dotnet add package <package>
- [ ] Create Seeder Class for <ClassNameToBeSeeded>
- mkdir Models/
- nano Models/classNameSeeder.cs
(or use your ide to manage files)
- [ ] Add data to be seeded in static methods
private static IList<ClassNameToBeSeeded> SeedData()
{
IList<ClassNameToBeSeeded> pages = new List<ClassNameToBeSeeded>();
pages.Add(new ClassNameToBeSeeded
{
variable = "something",
}
);
return pages;
}
- [ ] Add in call to persist objects through context
public static void SeedToDB()
{
var contextOptions = new DbContextOptionsBuilder<ContextName>()
.UseSqlServer("ConnectionString")
.Options;
var context = new ContextName(contextOptions);
context.Database.EnsureCreated();
var sections = classNameSeeder.SeedData();
context.<contextDbSet>.AddRange(sections);
context.SaveChanges();
}
- [ ] Call this in main
namespace Seeder
{
class Program
{
public static void Main(string[] args)
{
classNameSeeder.SeedToDB();
}
}
}
- [ ] Make sure your tables are created with migrations and run the program via
dotnet run
dotnet ef database update 0 --context <context>
dotnet ef database update --context <context>