EF Core
Getting started with EF Core
Getting started with EF Core
  • Introduction
    • What is an ORM
    • Entity Framework Core
    • EF Core architecture
    • EF Core Approaches
  • Basics of EF Core
    • Create the project
      • Create the model & context
    • Create migration
    • CRUD using EF
      • Creating many entities
      • Update & Delete
    • Adding a property
      • Add migration
  • Entity Relationships
    • Add related entity
      • Add Vehicle
      • Modify Student
      • Modify context
      • Add migration
    • Manipulate related data
  • Entity Configuration
    • Fluent APIs
      • Frequently used APIs
    • Data Annotations
      • Frequently used annotations
Powered by GitBook
On this page
  1. Basics of EF Core
  2. CRUD using EF

Creating many entities

PreviousCRUD using EFNextUpdate & Delete

Last updated 2 years ago

CtrlK
  • Create many entities
  • Retrieve 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();