简体   繁体   中英

Entity Framework Core - Call A Populate Extension Method Inside Include

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)...

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);

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM