Skip to content

M0BIN-V/SeedEasy

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

7 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

NuGet Package

Table of content

Installation

dotnet add package SeedEasy

Usage

1. Create Your Seeder by Implementing Seeder<>

To automate the process of seeding initial data into the database, you can implement the Seeder<> class for your entities.

public class UserSeeder : Seeder<User>
{
    public override async Task SeedAsync(CancellationToken ct)
    {
        if (DbSet.Any()) return;

        // Add initial data
        DbSet.Add(new User
        {
            FirstName = "Sara",
            LastName = "Sarara",
        });

        // Save changes to the database
        await Context.SaveChangesAsync(ct);
    }
}

2. Configure Your DbContext to Load Seed Data

Next, configure your DbContext to automatically load the seed data from your assembly during the application startup.

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
    // Load seed data from the current assembly
    optionsBuilder.AddSeedData(Assembly.GetExecutingAssembly());

    base.OnConfiguring(optionsBuilder);
}
  • AddSeedData automatically finds and executes all the seeders in the current assembly, ensuring that seed data is populated when the application starts.
  • This approach centralizes the seeding logic and allows you to add seed data without manually invoking seed methods.

More Complex Examples

In some cases, you may need to seed more complex data, such as creating relationships between entities. Here’s an example:

public class UserSeeder : Seeder<User>
{
    public override async Task SeedAsync(CancellationToken ct)
    {
        if (DbSet.Any()) return;

        var user = new User
        {
            FirstName = "Sara",
            LastName = "Sarara",
            // Adding related entities
            Roles = new List<Role>
            {
                new Role { Name = "Admin" },
                new Role { Name = "User" }
            }
        };

        DbSet.Add(user);
        await Context.SaveChangesAsync(ct);
    }
}
  • In this example, we’re seeding a User entity with related Role entities. This shows how to seed complex data with relationships between entities.

About

Seed your data easily

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages