Search code examples
javascriptc#asp.net-corefrontendapi-design

What would be the most efficient way of tracking deleted objects on the front-end and save these changes on server?


I am working on an application where the user(teacher) needs to update students enrolled in the class. On the front-end, the user can remove/add students and as well as update properties of the class(name, room, etc)

At the moment, I'm removing students from the class that were not included on the request. Similar idea for adding students.

   public async Task UpdateSectionEnrollment(long sectionId, List<long> students)
    {
        var sectionSchedule = await _scheduleRepository.GetAll()
                                   .Where(a => a.SectionId == sectionId)
                                   .ToListAsync();

        var allEnrolledUserIds = sectionSchedule.Select(a => a.UserId).ToList();

        //Add new students
        var newEnrollement = students.Except(allEnrolledUserIds);
        var removeStudents = allEnrolledUserIds.Except(students);

        // add new students to section enrollement
        foreach (var userId in newEnrollement)
        {
            await _scheduleRepository.InsertAsync(new SectionStudent(userId, sectionId));
        }

        var sections = sectionSchedule.Where(s => removeStudents.Any(id => id == s.Id));

        foreach (var section in sections)
        {
            await _scheduleRepository.DeleteAsync(section);
        }

        await CurrentUnitOfWork.SaveChangesAsync();
    }

Is there a better approach to do this operation? Should each add/remove student be executed on a single request instead of batch operation?


Solution

  • Questions that ask "what is the best" are typically off topic so try to avoid asking them..

    I'll take this Q as a "are there any obvious downsides to my approach": were I you I think I would include every student id and an instruction to add or remove, rather than have a "not mentioning it means remove it". I say this chiefly because by being concrete about the intention for a known student means that two front end clients that know of different students can build up a comprehensive picture on the (server i.e. the source of truth), whereas if you have a "remove any unmentioned" then the final resting state on the server in a case where there are two clients sending updates rather depends on which client spoke most recently. You can, of course, persist with a "not mention means remove" but hen you need a much more intense communication with multiple clients, making sure that each is up to date before they submit changes and it can become an overly complex exercise in concurrency management

    You might reasonably say "well, that will never apply in my situation - there will only ever be a single client and it is the source of truth" - and I could only point out that never is a very long time... :)