Search code examples
c#wpfentity-frameworknulllazy-loading

Class that is member of another class is always null


I am working on a C# WPF project using Entity Framework code first.

I have a class that has an instance of another class as its member. I am trying to access the value of a property of the member class. I can get the value this way:

var com = context.MyParentClass.Where(p => (p.Identity == id)).Select(c =>
                            new
                            {
                                id = c.Identity,
                                PropertyValue = c.MyChildClass.PropertyValue
                            }
                             );

                    foreach(var item in com)
                    {
                        string xx = item.PropertyValue;
                        MessageBox.Show(xx);
                    }

But when I try to get the value without the select, the member class is always null:

var com = db.MyParentClass.SingleOrDefault(b => b.Identity == id);
                    string xx = com.MyChildClass.PropertyValue; //MyChildClass is null
                    MessageBox.Show(xx);

Does anyone know what is going on here? How do I get around the null-problem?


Solution

  • You have to make sure that lazy loading is enabled or not.

    1. context.Configuration.ProxyCreationEnabled should be true.
    2. context.Configuration.LazyLoadingEnabled should be true.
    3. Navigation property should be defined as public, virtual. The context will NOT do lazy loading if the property is not defined as virtual.

    You can use Include for eager loading also. Thank you @CodeCaster for the suggestion.

    Reference: https://www.entityframeworktutorial.net/lazyloading-in-entity-framework.aspx