Challenge Solution: Save Data

Review the solution to save data to a school database.

Solution

The project below demonstrates the solution to the challenge:

using Microsoft.EntityFrameworkCore;
using SaveData.Models.Entities;

namespace SaveData.Models.Data
{
    public class SchoolContext : DbContext
    {
        public SchoolContext()
        {

        }

        public SchoolContext(DbContextOptions<SchoolContext> options) : base(options)
        {

        }

        public virtual DbSet<Instructor> Instructors { get; set; }
        public virtual DbSet<Student> Students { get; set; }
        public virtual DbSet<Department> Departments { get; set; }
        public virtual DbSet<Course> Courses { get; set; }
        public virtual DbSet<StudentCourse> StudentCourses { get; set; }

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {

            if (!optionsBuilder.IsConfigured)
            {
                optionsBuilder.UseSqlite("data source=output/School.db");
            }
        }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity<Instructor>()
                        .HasOne(d => d.Department)
                        .WithMany(i => i.Instructors)
                        .HasForeignKey(inst => inst.DepartmentCode);

            modelBuilder.Entity<StudentCourse>().HasKey(sc => new { sc.StudentId, sc.CourseId });

            modelBuilder
                .Entity<StudentCourse>()
                .HasOne(sc => sc.Student)
                .WithMany(s => s.StudentCourses)
                .HasForeignKey(sc => sc.StudentId);

            modelBuilder
                .Entity<StudentCourse>()
                .HasOne(sc => sc.Course)
                .WithMany(c => c.StudentCourses)
                .HasForeignKey(sc => sc.CourseId);
        }

    }
}
Solution to save data

Click the “Run” button in the solution above, then execute the command below in the terminal:

Press + to interact
dotnet run

Below is a snippet from the output:

Press + to interact
---DEPARTMENTS---
TITLE HOD
Computer Science Fraser Jones
Business Management Jennifer Rock
---INSTRUCTORS---
FIRSTNAME LASTNAME DEPARTMENT
blessing Udoh Computer Science
Coleman Bale Computer Science
Benedict Okon Business Management
---COURSES---
TITLE DEPARTMENT
Information Systems Computer Science
Software Engineering Computer Science
Business Leadership Business Management
Digital Business Business Management
---STUDENTS---
FIRSTNAME LASTNAME DEPARTMENT
Ferdinand Mbotidem Computer Science
Margaret Olorunisola Business Management

Solution breakdown

Let’s review the solutions highlighted in the project.

Insert department and instructor data

Lines 35–38 of SchoolContext.cs indicate that there is a one-to-many relationship between departments and instructors. For this reason, we can insert them into the database as a related graph of entities.

Note the following from ...