bilpor
bilpor

Reputation: 3921

EF6 Turning off Lazy Loading returns null

before I set lazyloading to false. My query returned the correct values, but it brought half the DB with it. I have set lazyloading = false and I have removed the 'Virtual' from both models. But still it returns Null. Here's my code : The linq statement

public BasePremiumNotional GetBasePremiumNotional(int productVersionId, int bedrooms, string propertyType, int? startYear, int? endYear, DateTime version)
{
            BasePremiumNotional basePremiumNotional =
                GetSingle(t => t.ProductVersionId == productVersionId)
                    .BasePremiumNotionals.FirstOrDefault(
                        g => g.NoOfBedrooms == bedrooms && g.PropertyType == propertyType && g.StartYear == startYear && g.EndYear == endYear && g.Version == version.Date);
            return basePremiumNotional;
}

The GetSingle Method to make the actual call:

public T GetSingle(Expression<Func<T, bool>> predicate)
{
    var query = _entities.Set<T>().FirstOrDefault(predicate);
    return query;
}

In this instance T is the parent object ProductVersion and the child object is BasePremiumNotionals

Upvotes: 0

Views: 94

Answers (2)

Aditya Santoso
Aditya Santoso

Reputation: 1071

The problem with turning off Lazy Loading is that you have to explicitly tell which navigation properties you want to populate along with your query.

To Include the navigation properties along with the predicate, you can do:

    public T GetSingle<T>(Expression<Func<T, bool>> predicate,
               params Expression<Func<T, object>>[] navigationProperties)
    {            
        IQueryable<T> query = _entities.Set<T>();
        foreach (var navigationProperty in navigationProperties)
        {
            query = query.Include(navigationProperty);
        }
        return query.FirstOrDefault(predicate);
    }

And assuming an entity that looks like this:

    public class FooBar
    {
        public int ProductVersionId { get; set; }

        public ICollection<BasePremiumNotional> BasePremiumNotionals { get; set; }
    }

You can use it as such:

var foo = GetSingle<FooBar>(t => t.ProductVersionId == productVersionId, 
                       n => n.BasePremiumNotionals)

Upvotes: 0

Giorgi
Giorgi

Reputation: 30883

Turning lazy loading off won't automagically preload the navigation properties with it. In order to get the navigation properties too you need to Include them in your query.

Upvotes: 2

Related Questions