none
Object Data Not Showing RRS feed

  • Question

  • Total noob trying to learn EF.

    Set up two simple classes as follows:

    public class Student
        {
            public int StudentId { get; set; }
            public string Name { get; set; }
            public int Age { get; set; }
            public Address MyAddress { get; set; }
        }

        public class Address
        {
            public int AddressID { get; set; }

            public string Street { get; set; } = "";
            public string City { get; set; } = "";

        }

    Using code first and migrations.  The migration sets up a MyAddress.AddressID field in the Students DB.  Entered (through code) some sample data.  I confirmed that it's in the database tables.

    I ask for the Students data:

    var context = new SchoolContext()
    var wk2 = context.Students.ToList();
    
    


    wk2[0].MyAddress.Street & City debugs as null.  (Other Student data is there.) Shouldn't the MyAddress object be populated with data that is in the Addresses database table?


    Tuesday, June 18, 2019 5:46 PM

Answers

  • OK, have the answer.

    Have to "Include" the nested entity as such:

    var wk2 = context.Students.Include(x=>x.MyAddress).ToList();


    • Marked as answer by wgcampbell Wednesday, June 19, 2019 2:20 PM
    Tuesday, June 18, 2019 9:01 PM

All replies

  • OK, have the answer.

    Have to "Include" the nested entity as such:

    var wk2 = context.Students.Include(x=>x.MyAddress).ToList();


    • Marked as answer by wgcampbell Wednesday, June 19, 2019 2:20 PM
    Tuesday, June 18, 2019 9:01 PM
  • Hi wgcampbell,

    I am glad you have got your solution. We appreciated you shared us your solution. And we also hope you can mark it as an answer. By marking a post as Answered, you help others find the answer faster.

    Regards,

    Kyle


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Wednesday, June 19, 2019 1:23 AM
    Moderator