【问题标题】:how to desactivate lazy loading for entity framework 6如何为实体框架 6 停用延迟加载
【发布时间】:2014-11-11 21:59:34
【问题描述】:
public class Country : Item
{
    public string           Code
    {get; set;}

    public string CodePhone
    { get; set; }
    public string           Name
    {get; set;}
    public string Flag
    { get; set; }
    public decimal?         Latitude
    {get; set;}
    public decimal?         Longitude
    {get; set;}

    public int              RegionsCount
    {get; set;}

    [ForeignKey("DefaultCurrency")]
    public int? DefaultCurrencyID
    {get; set;}
    public virtual Currency DefaultCurrency
    { get; set; }

    public ContinentType ContinentType
    { get; set; }

    public virtual ICollection<Property> 
                            Properties 
    {get; set;}

    public ICollection<CountryLocale>
                            CountryLocales
    { get; set; }
}

public class CountryLocale : ItemLocale
{
    [ForeignKey("Country")]
    public int                  CountryID
    {get; set;}

    public Country
                            Country
    {get; set;}

    public string                   FullName
    {get;set;}
}

 public TEntity Get(Expression<Func<TEntity, bool>> where, params string[] includes)
    {
        var model = this.DbSet;

        foreach (var property in includes)
        {
            model.AsExpandable().Include(property);
        }

        return model.Where(where).FirstOrDefault();
    }

this.Configuration.LazyLoadingEnabled = false;
        this.Configuration.ProxyCreationEnabled = false;

Country country = this._CountryRepository.Get(p=>p.ID ==  this.CountryID, new string[] { "CountryLocales" });

值不能为空。 参数名称:来源

说明:在执行当前 Web 请求期间发生未处理的异常。请查看堆栈跟踪以获取有关错误及其源自代码的位置的更多信息。

异常详细信息:System.ArgumentNullException:值不能为空。 参数名称:来源 line : CountryLocale countrylo = country.CountryLocales.First();

出于性能原因,我在尝试停用延迟加载时遇到此错误。我该如何解决这个问题?提前致谢。

【问题讨论】:

    标签: asp.net-mvc-5 lazy-loading entity-framework-6


    【解决方案1】:

    当您禁用 LazyLoading 时,您需要使用 Include 手动加载主对象的子属性

    var country = db.Country.Include("CountryLocales");
    

    另一种方法是:

    • 不要禁用延迟加载并在查询中使用include

    • 尝试将您的孩子对象一一包括在内,直到您感觉到 性能更好。

    • 通常如果你知道你会迭代一个 您应该在查询中使用 include 的子对象 对象。

    • 如果您需要访问该级别的属性,请记住包含二级子级...Include("Parent.Child")

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-20
      相关资源
      最近更新 更多