Search code examples
c#sqlentity-frameworkscaffolding

Generated model classes does not contain referenced objects


I am trying to use scaffolding to make a database-first application but have run into a problem.

Using the database as specified here:

CREATE TABLE Group (
    Id UNIQUEIDENTIFIER NOT NULL PRIMARY KEY,
    ...
);

CREATE TABLE Person ( 
    Id UNIQUEIDENTIFIER NOT NULL PRIMARY KEY,
    GroupId UNIQUEIDENTIFIER FOREIGN KEY REFERENCES Group(Id) NOT NULL,
    ...
);

I generate classes for accessing the database using scaffold. But the generated Group class does give access to the persons in the group. If I try to access the persons in a group like this:

var personsInGroup = myGroup.Persons.ToList();

The personsInGroup-list is empty, even though if I check the database, all the Persons have a GroupId.

Instead I have to find the persons in the group like this:

var personsInGroup = context.Persons.Where(p => p.GroupId == myGroup.Id).ToList();

Am I doing something wrong or have I misunderstood how these generated classes work?


Solution

  • @David Browne pointed me to read up on Loading Related Data, where I, indeed, found the answer to my question.

    The trick was to specify that I want the Person data when I get the Group data from the database. It can be done like this:

    var group = context.Groups
        .Include(g => g.Persons)
        .First();
    
    var personsInGroup = group.Persons;