EF Meny-To-Meny relation Circular loading RRS feed

  • Question

  • Hi, 

    Lets say I have EntityA that have  multiple of EntityB and EntityB can have multiple of EntityA. For simplicity:

    class Student {

    public string Name {get;set;} public virtual ICollection<Teacher> Teachers{get;set;} } class Teacher {

    public string Name {get;set;} public virtual ICollection<Student> Students{get;set;} }

    I do mapping like this:

    HasMany(x => x.Teachers)
       .WithMany(x => x.Students)
       .Map(x => 

    Lazy loading is turned of. 

    Then I want to load Student including Teachers (meaning only Name of Teacher) but not other Students and then Teachers curculary. I tried this.

    var student = _context.Students.Where(x => x.Name == studentName)

    But I really get a objects. I only want to load the first level.

    How can I do this?


    Thursday, October 13, 2016 11:16 AM

All replies

  • Hi Novak Savic,

    >>But I really get a objects. I only want to load the first level. How can I do this?

    According to your description, it seems that we could return a custom result like this:

    using (var db = new EFDemoContext())
                    string studentName = "Cole";
                    var student = db.Students.Where(x => x.Name == studentName)
                     .Select(s => new
                         StudentId = s.StudentId,
                         Name = s.Name,
                         Teachers = s.Teachers.Select(t=>t.Name)
                    foreach (var item in student.Teachers)
                        Console.Write("{0}", item);

    Best regards,

    Cole Wu

    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click HERE to participate the survey.

    Friday, October 14, 2016 7:04 AM