Jamie Rees
Jamie Rees

Reputation: 8183

Entity Framework model issue

I am having some strange issues, I am attempting to pull a record out of the database and it seems like most of it is null even know if I manually look in the DB it's populated.

Model

public class AdminConfiguration : Entity // Entity is an abstract class containing an ID
{
    public bool Authentication { get; set; }
    public List<ApplicationConfiguration> ApplicationConfiguration { get; set; }
    public List<LinksConfiguration> LinksConfiguration { get; set; }
    public EmailConfiguration EmailConfiguration { get; set; }
    public bool WakeOnLan { get; set; }
}

Basically any reference to another class is null The only thing that is populated is the WakeOnLan property.

Query

    public AdminConfiguration Find(int id)
    {
        return Db.AdminConfiguration.Find(id);
    }

I have a feeling I have a misunderstanding regarding how I set up the models. I am expecting the query to return me a fully populated AdminConfiguration object.

Upvotes: 0

Views: 37

Answers (2)

CoOl
CoOl

Reputation: 2797

The best way to setup your model is:

public class AdminConfiguration : Entity // Entity is an abstract class containing an ID
{
    public AdminConfiguration()
    {
        this.ApplicationConfigurations = new HashSet<ApplicationConfiguration>();
        this.LinksConfigurations = new HashSet<LinksConfiguration>();
    }
    public bool Authentication { get; set; }
    public EmailConfiguration EmailConfiguration { get; set; }
    public bool WakeOnLan { get; set; }

    // Navigation properties
    public virtual ICollection<ApplicationConfiguration> ApplicationConfigurations { get; set; }
    public virtual ICollection<LinksConfiguration> LinksConfigurations { get; set; }
}

Upvotes: 1

Anton K
Anton K

Reputation: 176

Try to set navigation properties as virtual to enable lazy loading:

public virtual List<ApplicationConfiguration> ApplicationConfiguration { get; set; }

Please refer to https://msdn.microsoft.com/en-us/data/jj193542.aspx

This enables the Lazy Loading feature of Entity Framework. Lazy Loading means that the contents of these properties will be automatically loaded from the database when you try to access them.

Upvotes: 2

Related Questions