how to seed data in EF
public class SchoolContext: DbContext
{
public SchoolContext(): base("SchoolDB")
{
Database.SetInitializer(new SchoolDBInitializer());
}
public DbSet<Student> Students { get; set; }
public DbSet<Standard> Standards { get; set; }
}
public class SchoolDBInitializer : DropCreateDatabaseAlways<SchoolDBContext>
{
protected override void Seed(SchoolDBContext context)
{
IList<Standard> defaultStandards = new List<Standard>();
defaultStandards.Add(new Standard() { StandardName = "Standard 1", Description = "First Standard" });
defaultStandards.Add(new Standard() { StandardName = "Standard 2", Description = "Second Standard" });
defaultStandards.Add(new Standard() { StandardName = "Standard 3", Description = "Third Standard" });
context.Standards.AddRange(defaultStandards);
base.Seed(context);
}
}
4
1
// This method of seeding is creating another Project alongside your webApi
* 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
//Class or Object to be seeded
private static IList<ClassNameToBeSeeded> SeedData()
{
IList<ClassNameToBeSeeded> pages = new List<ClassNameToBeSeeded>();
// Creating objects here to pass into the context
pages.Add(new ClassNameToBeSeeded
{
// These have to match the unmapped variables in your context
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)
{
//Its static so no need to instantiate
classNameSeeder.SeedToDB();
}
}
}
- [ ] Make sure your tables are created with migrations and run the program via
dotnet run
//Useful methods for database manipulation
// reset migration for table
dotnet ef database update 0 --context <context>
//run migration for table creation
dotnet ef database update --context <context>
Thank you!
1
0
4.13
8
// This method of seeding is creating another Project alongside your webApi
* 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
//Class or Object to be seeded
private static IList<ClassNameToBeSeeded> SeedData()
{
IList<ClassNameToBeSeeded> pages = new List<ClassNameToBeSeeded>();
// Creating objects here to pass into the context
pages.Add(new ClassNameToBeSeeded
{
// These have to match the unmapped variables in your context
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)
{
//Its static so no need to instantiate
classNameSeeder.SeedToDB();
}
}
}
- [ ] Make sure your tables are created with migrations and run the program via
dotnet run
//Useful methods for database manipulation
// reset migration for table
dotnet ef database update 0 --context <context>
//run migration for table creation
dotnet ef database update --context <context>
Thank you!
8
0
0
1
// it goes into class ApplicationDbContext : DbContext
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Author>().HasData(
new Author
{
AuthorId = 1,
FirstName = "William",
LastName = "Shakespeare"
}
);
modelBuilder.Entity<Book>().HasData(
new Book { BookId = 1, AuthorId = 1, Title = "Hamlet" },
new Book { BookId = 2, AuthorId = 1, Title = "King Lear" },
new Book { BookId = 3, AuthorId = 1, Title = "Othello" }
);
/*further relational instructions may come here, like:
modelBuilder.Entity<Author>()
.HasMany<Book>(a => a.Books)
.WithOne(b => b.Author)
.HasForeignKey(b => b.AuthorId);
}
Thank you!
1
0
Are there any code examples left?
New code examples in category C#
-
C# 2022-03-27 22:40:23 c# movement script
-
C# 2022-03-27 22:15:17 Delete last modification on EntityFramework Core
-
C# 2022-03-27 22:15:02 file.create folder c#
-
C# 2022-03-27 19:25:04 Error inflating class android.support.constraint.ConstraintLayout
-
C# 2022-03-27 19:15:02 top down shooting in unity 2D
-
C# 2022-03-27 18:50:02 c# remove invalid directory characters
-
C# 2022-03-27 18:30:07 how to use K2 games Games parallax background
-
C# 2022-03-27 18:25:10 c# replace crlf
-
C# 2022-03-27 18:25:09 keycode for left mouse click unity