Entity Framework Core - Call A Populate Extension Method Inside Include

c# entity-framework-6 entity-framework-core

Question

I will explain my issue using an example. Lets say I have this following classes and methods (I created them only for this example)

  public class Student
    {
        public string Name { get; set; }
        public string Id { get; set; }

        public Subject Expertise { get; set; }
    }

    public class Subject
    {
        public string Name { get; set; }
        public Teacher Teacher { get; set; }
    }

    public class Teacher
    {
        public string Name { get; set; }
        public string LicenseId{ get; set; }
        public License License { get; set; }

    }
    public class License
    {
        public string LicsenseType;
    }

    public static IQueryable<Subject> PopulateWithTeacherAndLicense(this IQueryable<Subject> subjects)
    {

        return subjects
            .Include(c => c.Teacher)
                .ThenInclude(p => p.License);
        
    }

Now lets assume I want to select all students with all their subject,teacher and license. In order to do so, I want to use my PopulateWithTeacherAndLicense. I want the query to look something like:

db.Students.Include(s => s.Expertise.PopulateWithTeacherAndLicense())

And not have to do Include(s=>s.Expertise).TheInclude(s => s.Teacher)...

1
0
1/21/2019 10:36:01 AM

Popular Answer

You can create extension method for Student collection itself

public static IQueryable<Student> IncludeExpertise(this IQueryable<Student> students)
{
    return students
        .Include(s => s.Expertise)
        .ThenInclude(c => c.Teacher)
        .ThenInclude(p => p.License);

}
0
1/22/2019 7:29:07 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow