简体   繁体   English

EF6关闭延迟加载将返回null

[英]EF6 Turning off Lazy Loading returns null

before I set lazyloading to false. 在将lazyloading设置为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. 我设置了lazyloading = false,并且从两个模型中都删除了“虚拟”。 But still it returns Null. 但是它仍然返回Null。 Here's my code : The linq statement 这是我的代码:linq语句

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: 进行实际调用的GetSingle方法:

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 在这种情况下, T是父对象ProductVersion ,而子对象是BasePremiumNotionals

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. 为了也获得导航属性,您需要在查询中包括它们

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: 要将导航属性和谓词Include在内,您可以执行以下操作:

    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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM