none
Nested collection list with multiple tables in entity framework RRS feed

  • Question

  • Hi,

    I have declared 2models  

    [Table("Students")]
    public class StudentModel
    {
    [Key]
    public int sid {get;set;}
    public string name {get;set;}
    public List<AddressModel> address {get;set;}

    }

    [Table("Address")]
    public class AddressModel
    {
    [Key]
    public int addid {get;set;}
    public string description {get;set;}
    public int sid {get;set;} --foreign key
    }



    In my controller :

        public class StudentsController : Controller
        {
            //
            // GET: /Students/

            public ActionResult Index()
            {
                IList<StudentModel> students = new List<StudentModel>();
                StudentContext studentContext = new StudentContext();
                students = studentContext.Students.ToList<StudentModel>();
                return View();
            }
    }

    Here the students collection is getting the list of student and the address field is returning null.

    As the StudentModel has the List<AddressModel> collection, I need to populate the list of address for each student. So Each student in list of students in turn should contain list of address for that student.

    Can anyone help me to findout where am I going wrong.

    Not sure if the models which i have declared are correct or not.


    Thanks in advance

    Pavan

    Friday, July 3, 2015 1:16 PM

Answers

  • You could use eager loading to load the related entities:

        public ActionResult Index()
        {
            IList<StudentModel> students = new List<StudentModel>();
            StudentContext studentContext = new StudentContext();
            students = studentContext.Students.Include(s => s.address).ToList<StudentModel>();
            return View();
        }

    Please refer to the following page for more information about how to load related entities: https://msdn.microsoft.com/en-us/data/jj574232.aspx

    Hope that helps.

    Please remember to close your threads by marking helpful posts as answer and then start a new thread if you have a new question. Please don't ask several questions in the same thread.

    Friday, July 3, 2015 3:44 PM