c# - Entityframework Load certain columns of a list withing a entity -


heey, lets assume have teacher , student relation, teacher responsible group of students. lets want load information of teacher, given or id, including students teacher responsible for, students want load column containing name, not age , studentnumber (see below). question is, how that?

in attempt solve problem found https://colinmackay.scot/2011/07/31/getting-just-the-columns-you-want-from-entity-framework/ , similar situation, example shown in link return list of strings, want teacher returned.

classes:

public class schoolcontext : dbcontext {     public dbset<teacher> teachers { { return set<teacher>(); } } }   public class teacher {     [key]     public int id { get; private set; }     public string name { get; set; }     public list<students> students { get; set; } }    public class students {     [key]     public int databaseid { get; private set; }     public int studentnumber { get; set; }     public string name { get; set; }     public int age { get; set; } } 

example of loading:

    private static void main(string[] args)     {         var teacher = loadteacher(4);         foreach(var student in teacher.students)         {            console.writeline(student.name);         }     }       public static teacher loadteacher(int teacherid)     {         using (var context = new schoolcontext())         {             return context.teachers.where(t => t.id == teacherid)                                    .firstordefault();                                    //at part question, how make sure name of students loaded , not age , studentnumber?           }     } 

you have select in context want return. , return anonymous object

like this:

public static iqueryable loadteacher(int teacherid) {     using (var context = new schoolcontext())     {         var retval = teacher in context.teachers                      teacher.id == teacherid                      select new {                            teacher = teacher,                            studentnames = student in teacher.students                                           select student.name                            }          return retval;     } } 

then can access object calling method.


Comments

Popular posts from this blog

magento2 - Magento 2 admin grid add filter to collection -

Android volley - avoid multiple requests of the same kind to the server? -

Combining PHP Registration and Login into one class with multiple functions in one PHP file -