Instantly share code, notes, and snippets.

@vkhorikov /1.cs
Last active Sep 8, 2018

Embed
What would you like to do?
In Defense of Lazy Loading
public class Student : Entity
{
public virtual string Name { get; set; }
public virtual decimal TotalDebt { get; set; }
public virtual IList<Enrollment> Enrollments { get; set; }
public virtual IList<SportsActivity> SportsActivities { get; set; }
}
public class Enrollment : Entity
{
public virtual Student Student { get; set; }
public virtual Course Course { get; set; }
public virtual Grade Grade { get; set; }
}
public enum Grade
{
A = 1, B = 2, C = 3, D = 4, F = 5
}
public class Course : Entity
{
public virtual string Name { get; set; }
public virtual int Credits { get; set; }
}
public class SportsActivity : Entity
{
public virtual Sports Sports { get; set; }
public virtual DateTime PlayingSince { get; set; }
}
public class Sports : Entity
{
public virtual string Name { get; set; }
}
public IActionResult Disenroll(long studentId, int enrollmentNumber)
{
Student student = _studentRepository.GetById(studentId);
Enrollment enrollment = student.Enrollments[enrollmentNumber];
student.Enrollments.Remove(enrollment);
return Ok();
}
-- Roundtrip 1
SELECT *
FROM dbo.Student s
WHERE s.StudentID = @StudentID
-- Roundtrip 2
SELECT *
FROM dbo.Enrollment e
WHERE e.StudentID = @StudentID
-- Roundtrip 1
SELECT *
FROM dbo.Student s
INNER JOIN dbo.Enrollment e ON s.StudentID = e.StudentID
INNER JOIN dbo.Course c ON e.CourseID = c.CourseID
WHERE s.StudentID = @StudentID
SELECT *
FROM dbo.SportsActivity a
INNER JOIN dbo.Sports s ON a.SportsID = s.SportsID
WHERE a.StudentID = @StudentID
public IActionResult Enroll(long studentId, string sportsName)
{
Sports sports = _sportsRepository.GetByName(sportsName);
Student student = _studentRepository.GetById(studentId);
if (student.TotalDebt > 10000M)
return Error($"Cannot enroll into {sportsName}, too much debt");
student.SportsActivities.Add(new SportsActivity
{
PlayingSince = DateTime.Now,
Sports = sports
});
return Ok();
}
public sealed class StudentRepository
{
public Student GetByIdWithEnrollments(long studentId)
{
/* Load only enrollments */
}
public Student GetByIdWithSportActivities(long studentId)
{
/* Load only sport activities */
}
public Student GetByIdWithEnrollmentsAndSportActivities(long studentId)
{
/* Load everything */
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment