In my previous post, we talked about data access and updates in entity framework.

A naive way to update related data, especially when the context isn’t tracking your object, as in, you send data about an existing entity in the database, from the UI, and EF has to figure out what part of the updated record has changed and needs an update in the database.

If you ever encounter a situation where you are to update only one related object of a primary entity, then you might be in for a surprise. I am going to use an example that I followed to understand this from Julie Lerman’s Pluralsight course on EFCore 3. I have never had to do this personally in the round-about way that the example states. However, I am pretty sure I might end up with tricky situations as I spend more time with EF.

    /*
    // this is probably only ever done for a demonstration. 
    // Had I known which quote I needed to modify, I would have fetched that directly
    // and modified it. Not done it this way.
    // The SQL generated for the following savechanges, would be specifically related // to the Quote that was modified. Because the Change Tracker is in scope, 
    // everything is as expected.
    */
    private static void ModifyingRelatedDataWhenTracked()
    {
        var philosopher = _context.Philosophers.Include(p => p.Quotes).FirstOrDefault(p=> p.id==2);
        philosopher.Quotes[0].Text = "Did you hear that?";
        _context.SaveChanges();
    }
    
    /*
    // I doubt anyone would do something like this.
    // This is a roundabout way of updating a related record.
    // the sql generated for this one, will surprisingly update every quote
    // associated to the philosopher, which is ridiculous and not obvious to 
    // anyone reading the c# code below
    */
    private static void ModifyingRelatedDataWhenNotTracked()
    {
        var philosopher = _context.Philosophers.Include(s => s.Quotes).FirstOrDefault(s=> s.id==2);
        philosopher.Quotes[0].Text = "Did you hear that?";
        var quote = philosopher.Quotes[0];
        using(var newContext = new PhilosopherContext())
        {
            newContext.Quotes.Update(quote);
            newContext.SaveChanges();
        }
    }
    
    /*
     * How on earth do we get around it? If you thought you could use Attach(),
     * then you are wrong. I thought the same too. But nope. Apparently in this
     * scenario, Attach() would mark all as unchanged!
     * The solution, use the DbContext's Entry() method.
    */
    private static void ModifyingRelatedDataWhenNotTracked()
    {
        var philosopher = _context.Philosophers.Include(s => s.Quotes).FirstOrDefault(s=> s.id==2);
        philosopher.Quotes[0].Text = "Did you hear that?";
        var quote = philosopher.Quotes[0];
        using(var newContext = new PhilosopherContext())
        {
            // Entry focuses specifically focuses on the entity passed to it
            newContext.Entry(quote).State = EntityState.Modified;
            newContext.SaveChanges();
        }
    }

Interacting with Many to many relationships

Let us revisit the Student and Courses example in part 1. I will paste the code below to refresh your memory.

    // the mapping/join table that connects students with courses
    // and vice versa
    public class StudentCourse
    {
        public int StudentId { get; set; }
        public Student Student { get; set; }
    
        public int CourseId { get; set; }
        public Course Course { get; set; }
    }
    
    public class Student
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public IList<StudentCourse> StudentCourses { get; set; }
    }
    
    public class Course
    {
        public int Id { get; set; }
        public string CourseName { get; set; }
        public IList<StudentCourse> StudentCourses { get; set; }
    }

Both Student and Course have a navigation property StudentCourses to easily fetch the courses that a student has signed up for and also the students that have signed for a course. This is a good real world, many to many relationship example.
So in this example, although there is a StudentCourse join table, it is not added to the DbContext as a separate DbSet for direct modification. This means you cannot use context.StudentCourses.Add() to add a record there. You have to add a record via the main entity’s navigation property. So what do you do now?
DbContext.Add() to the rescue.

    private static void AddStudentCourse(int studentId, int courseId)
    {
        var studentCourseJoin = new StudentCourse { StudentId = studentId, CourseId = courseId; };
        dbContext.Add(studentCourseJoin);
        dbContext.SaveChanges();
    }

What if you have a course and you want to say, a student has joined this course? If the context is tracking all changes in the scope, then you can do this as follows:

    /* 
     * as EF is tracking changes, by writing the following code, 
     * EF will be able to find out that this Student is enlisted 
     * for the course fetched earlier.
    */
    private static void EnlistStudentIntoCourse()
    {
        var course = dbContext.Courses.Find(1);
        course.StudentCourses.Add(new StudentCourse { StudentId = 2 } );
        dbContext.SaveChanges();
    }

So now that you have done a direct insert and a related insert into the StudentCourses join table, let us take a look at the Delete.

    /*
     * Code is very similar to the Add written earlier, except that this time we use Remove method instead. 
    */
    private static void RemoveStudentCourse(int studentId, int courseId)
    {
        var studentCourseJoin = new StudentCourse { StudentId = studentId, CourseId = courseId; };
        dbContext.Remove(studentCourseJoin);
        dbContext.SaveChanges();
    }

Querying many-to-many relationships

As EFCore forces you to have a join table, it is useful to think about querying many-to-many relationships as querying a parent, child and grandchild at once.

If you are querying based on Student, then Student is the parent, StudentCourse is the Child and the Course would be the grand child.

This can be queried using a special combination.

    /*
     * One way to do this.
     * The downside to this is that to access courses, you 
     * have to navigate through two levels 
    */
    private static void GetStudentWithCourses()
    {
        var studentWithCourses = dbContext.Students
            .Include(s => s.StudentCourses)
            .ThenInclude(sc => sc.Course)
            .FirstOrDefault(s => s.Id == 2);
    }
    
    /*
     * Another way to do the exact same thing, probably clearer
    */
    private static void GetStudentWithCoursesUsingProjections()
    {
        var studentWithCourses = dbContext.Students.Where(s => s.Id == 2)
            .Select(s => new 
            {
                Student = s,
                Courses = s.StudentCourses.Select(sc => sc.Course)
            })
            .FirstOrDefault();
    }

Persisting Data in One to One

Let us first set the stage for this one with an example scenario, so that it is easier to understand what I am trying to talk about.

    /*
     * The University has decided to issue every sutdent with an IPad
     * this information is now stored like this
    */
    public class Student
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public IList<StudentCourse> StudentCourses { get; set; }
        // every student has an university registered ipad
        public IPad IPad { get; set; }
    }
    
    /*
     * IPads have a studentId in them to map back to the Student but no navigation property to retrieve a student record directly
    */
    public class IPad
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public int StudentId { get; set; }
    }

In this case, EF will also create a unique foreign key constraint when you try and generate the database creation scripts for this one. So that every studentId in the IPad table is unique.

Let us see how to add a new student with a new IPad

    /*
     * The most straightforward way of adding one entity and its
     * related entity in one go for a 1-1 relationship
     * SQL would be to insert into Students, get identity, and insert into IPads with that id.
    */
    private static void AddNewStudentWithIpad()
    {
        var student = new Student { Name = "Barrack Obama" };
        student.IPad = new IPad { Name = "Barrack's Ipad" };
        dbContext.Students.Add(student);
        dbContext.SaveChanges();
    }

But many students in the University currently do not have an official IPad yet. They are only getting this now. So how do we just add an IPad record for an existing student?

    /*
     * Not complicated. Still simple
    */
    private static void AddNewIpadToExistingStudentUsingId()
    {
        var iPad = new IPad { Name = "Michelle's Ipad", StudentId = 2 };
        // use dbcontext add, as there are no DbSets defined for IPads yet
        dbContext.Add(iPad);
        dbContext.SaveChanges();
    }
    
    /*
     * What if you had the Student object in memory? That would be dead simple!
    */
    private static void AddNewIpadToExistingStudentInMemory()
    {
        var student = dbContext.Students.Find(2);
        // associate an IPad record to this student
        student.IPad = new IPad { Name = "Barrack's Ipad" };
        dbContext.SaveChanges();
    }
    
    /*
     * What if you had the Student object in memory? But then this is a different 
     * context? use the Attach Method to let EF know that this is an existing object that is being modified! EF Core will identify that student has an ID and IPad doesn't and generate the right query to insert just the Ipad record.
    */
    private static void AddNewIpadToExistingStudentInMemoryNewContext()
    {
        var student = dbContext.Students.AsNoTracking().FirstOrDefault(s => s.Id == 2);
        // associate an IPad record to this student
        student.IPad = new IPad { Name = "Barrack's Ipad" };
        using(var newContextForDemo = new UniversityContext())
        {
            newContextForDemo.Attach(student);
            newContextForDemo.SaveChanges();
        }
    }

Well, those were the most important bits for working with related data.

In the next post, we’ll look at how we can work with Stored Procedures and Raw SQL.