Creating many entities

Create many entities

Instead of creating one entity at a time as shown before we can create or save several entities at once using the AddRange method as shown below

Replace the Program code with the one shown below

using EFGetStarted;
using System;
using System.Linq;

var db = new MyContext();

Console.WriteLine("Creating many students...");

var students = new List<Student>()
{
    new Student()
    {
        Name = "Sam",
        IsEnrolled = true
    },

    new Student()
    {
        Name = "Ted",
        IsEnrolled = false
    },
    new Student()
    {
        Name = "Kim",
        IsEnrolled = false
    }
};

db.Students.AddRange(students);
db.SaveChanges();

Console.WriteLine("Press any key to exit");
Console.ReadKey();

If we now take a look at the database we should see several rows in the Students table

Retrieve many entities

If we wanted to display the information about all the students present in our database, we can loop through the entities as shown below

Replace the Program code with the one shown below

using EFGetStarted;
using System;
using System.Linq;

var db = new MyContext();

Console.WriteLine("List of students...\n");

foreach (var s in db.Students)
    Console.WriteLine($" Id: {s.Id}\t Name: {s.Name} Is Enrolled: {s.IsEnrolled}");

Console.WriteLine();
Console.WriteLine("Press any key to exit");
Console.ReadKey();

Last updated