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

		&lt;ItemGroup&gt;
          &lt;ProjectReference Include=&quot;..\path\name.csproj&quot; /&gt;
        &lt;/ItemGroup&gt;
        
     - Add needed EF packages with dotnet add package &lt;package&gt;
    
  - [ ] Create Seeder Class for &lt;ClassNameToBeSeeded&gt;
       - 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&lt;ClassNameToBeSeeded&gt; SeedData()
        {
            IList&lt;ClassNameToBeSeeded&gt; pages = new List&lt;ClassNameToBeSeeded&gt;();

            // Creating objects here to pass into the context
    
            pages.Add(new ClassNameToBeSeeded
               {
                // These have to match the unmapped variables in your context
                variable = &quot;something&quot;,
               }
            );

            return pages;
        }

  - [ ] Add in call to persist objects through context
  
       public static void SeedToDB()
        {
            var contextOptions = new DbContextOptionsBuilder&lt;ContextName&gt;()
                .UseSqlServer(&quot;ConnectionString&quot;)
                .Options;

            var context = new ContextName(contextOptions);
            context.Database.EnsureCreated();
            var sections = classNameSeeder.SeedData();
            context.&lt;contextDbSet&gt;.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 &lt;context&gt;

//run migration for table creation
dotnet ef database update --context &lt;context&gt;

4 (1 Votes)
0
4.13
8
Lomi 100 points

                                    // 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

		&lt;ItemGroup&gt;
          &lt;ProjectReference Include=&quot;..\path\name.csproj&quot; /&gt;
        &lt;/ItemGroup&gt;
        
     - Add needed EF packages with dotnet add package &lt;package&gt;
    
  - [ ] Create Seeder Class for &lt;ClassNameToBeSeeded&gt;
       - 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&lt;ClassNameToBeSeeded&gt; SeedData()
        {
            IList&lt;ClassNameToBeSeeded&gt; pages = new List&lt;ClassNameToBeSeeded&gt;();

            // Creating objects here to pass into the context
    
            pages.Add(new ClassNameToBeSeeded
               {
                // These have to match the unmapped variables in your context
                variable = &quot;something&quot;,
               }
            );

            return pages;
        }

  - [ ] Add in call to persist objects through context
  
       public static void SeedToDB()
        {
            var contextOptions = new DbContextOptionsBuilder&lt;ContextName&gt;()
                .UseSqlServer(&quot;ConnectionString&quot;)
                .Options;

            var context = new ContextName(contextOptions);
            context.Database.EnsureCreated();
            var sections = classNameSeeder.SeedData();
            context.&lt;contextDbSet&gt;.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 &lt;context&gt;

//run migration for table creation
dotnet ef database update --context &lt;context&gt;

4.13 (8 Votes)
0
0
1

                                    // it goes into class ApplicationDbContext : DbContext
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity&lt;Author&gt;().HasData(
        new Author
        {
            AuthorId = 1,
            FirstName = &quot;William&quot;,
            LastName = &quot;Shakespeare&quot;
        }
    );
    modelBuilder.Entity&lt;Book&gt;().HasData(
        new Book { BookId = 1, AuthorId = 1, Title = &quot;Hamlet&quot; },
        new Book { BookId = 2, AuthorId = 1, Title = &quot;King Lear&quot; },
        new Book { BookId = 3, AuthorId = 1, Title = &quot;Othello&quot; }
    );

   /*further relational instructions may come here, like:
        modelBuilder.Entity&lt;Author&gt;()
        .HasMany&lt;Book&gt;(a =&gt; a.Books)
        .WithOne(b =&gt; b.Author)
        .HasForeignKey(b =&gt; b.AuthorId);
}

0
0
Are there any code examples left?
Create a Free Account
Unlock the power of data and AI by diving into Python, ChatGPT, SQL, Power BI, and beyond.
Sign up
Develop soft skills on BrainApps
Complete the IQ Test
Relative searches
ef data seeding null entity framework generate seed data seeding in table using ef ef6 seed data seed data in database entity framework run seed data in entity framework how to seed data into database for testing in efcore seed method in entity framework seeding database entity framework how to seed data entity framework how to seed ef seeding in ef core Seed Data in EF 6 Code-First How does ef seeding data work entity framework seeding database ef seed method using own key ef seeder method using own key how create a sql file with seed data in ef seeding entity framework entity data seeding create seed data entity framework how to seed data in the data entity EF seeding data How to seed in Entity Framework Creating table and seeding in the same ef seed method for table ef ef seed method seed database ef 6 EF seeding how to seed data to database entity framework seed data in ef core how to seed data in ef core model seed ef ef seed data with automatic identity column ef seed data entity framework add migration with seed data ef core seed database on create ef core seed database ef core default add data code first ef core add default data ef core add default data asp net mvc code first seeding into database first create database seed .net core entity framework db seed .net core seeding database seed db with data from db populate ef core db with data from db ef core insert data in migration where is the seed method in entity framework entity framework seed data ef core seed ef core hasdata seed class c# ef core seed data without id easy way to seed data in entity framework seed data with .net core 3.1 seeddata with .net core 3.1 asp.net core seed database asp.net core identity seed database on model create entity framework populate database Do you need to seed data in a database .net core seed database seed c# db .NET Core Migrations not populating DB update database on seeding in ASP MVC .net update database on seeding EF COre seed example entity framework 6 seed data configuration.cs entity framework 6 seed data entity seed data in migrations configuration example seed ef core 5 seed entity framework seed entity framework core using c# code to create a mysql database from existing db and seed it with data .net seed database how to seed data in entity framework core on model creating entity framework seed ef core ApplicationDBContextSeed c# seeding explained seeding an inmemory databse seed in memory database ef core how to seed data in EF seed ef core entity framework core seed method ef core seeder NETCOREAPP 3.1 seeding data seed file asp net seeding data from config values asp.ent core asp.net core seed related data entity framerwork seed data asp.net core entity framerwork seed data seeding data to a table asp.net seeding data asp.net seed data entity frazmework ef core seed data without migration inserting data EF core via migration entity framework seed data with foureign key what is the use for seed data ef core seed data ef core add seed data ef core seed function ef using repository from console project .net core data seeder how to make migration not to create database entity framework seeding Microsoft.EntityFrameworkCore seed data migration seed data types entity framework core seed data how fill dbcontext in entity framework core seeder entity framework asp net core entity framework code data seeding ef core seeding seed database .net core c# .net entity framework prefill database .net database first seed data ef core seed data if not exists visual studio seeding update database net core seeding seed data to a generated tables entity framework without entity seed data to autogenerated tabled enity framework seed netcore seed data in entity framework ef core seed data c# dbcontext foreign key data seeding issue how to add update migration seed in dotnet core .net 5 seed command .net 5 seed c# ef seed related data c# ef seed data related c# ef seed data EF seed seeding in ef6 efcore hash class before insert ef migratio add seed data data seeding ef core add migration seed data seeding asp core 3.1 ef core seeding in onmodelcreating seed configuration asp.net c# seeding relayed data entity framework core database hasData method C#
Made with love
This website uses cookies to make IQCode work for you. By using this site, you agree to our cookie policy

Welcome Back!

Sign up to unlock all of IQCode features:
  • Test your skills and track progress
  • Engage in comprehensive interactive courses
  • Commit to daily skill-enhancing challenges
  • Solve practical, real-world issues
  • Share your insights and learnings
Create an account
Sign in
Recover lost password
Or log in with

Create a Free Account

Sign up to unlock all of IQCode features:
  • Test your skills and track progress
  • Engage in comprehensive interactive courses
  • Commit to daily skill-enhancing challenges
  • Solve practical, real-world issues
  • Share your insights and learnings
Create an account
Sign up
Or sign up with
By signing up, you agree to the Terms and Conditions and Privacy Policy. You also agree to receive product-related marketing emails from IQCode, which you can unsubscribe from at any time.
Creating a new code example
Code snippet title
Source