如何在实体框架中加载特定对象

时间:2016-07-18 22:36:34

标签: c# entity-framework

我有一个自动生成的类(Orders类),它引用其他对象。我想要完成的是得到 使用订单ID和与该订单相关的用户的订单。

然而,在加载对象时,需要2秒钟来加载它。我查看了对象,EF正在填充列表 所有依赖对象(语言,国家,客户用户)。

我如何只获得特定对象,例如订单属性和用户对象?我试图用它完成 下面的代码,但它正在加载所有对象。

//Code for getting order id and user related to it
    using (var _storeEntities = new StoreEntities())
    {
    var test = _storeEntities.Orders.Where(r => r.Id.ToString() == orderId).Include(x => x.User).ToList();
    }



// Parent entity
    public partial class StoreEntities: DbContext
    {
    public virtual DbSet<Orders> Orders { get; set; }
    }

// Order object     
    public partial class Orders
    {
     public System.Guid Id { get; set; }
     public bool IsActive { get; set; }
     public System.DateTime OrderDate{ get; set; }
     public Nullable<int> CustomerId { get; set; }
     public string LanguageId { get; set; }
     public Nullable<System.Guid> UserId { get; set; }
     public string CountryId { get; set; }

     public virtual Customer Customer{ get; set; }
     public virtual User User{ get; set; }
     public virtual Country Country { get; set; }
     public virtual Language Language { get; set; }
     }

2 个答案:

答案 0 :(得分:2)

您应该在配置中禁用延迟加载

public class YourContext : DbContext 
{ 
    public YourContext () 
    { 
        this.Configuration.LazyLoadingEnabled = false; 
    } 
}

或仅在通话期间

    using (var _storeEntities = new StoreEntities())
        {
      _storeEntities .Configuration.LazyLoadingEnabled = false;

        var test = _storeEntities.Orders.Where(r => r.Id.ToString() == orderId)
                                        .Include(x => x.User).ToList();
        }

以下是每种加载类型的MSDN文章

https://msdn.microsoft.com/en-nz/data/jj574232.aspx

答案 1 :(得分:2)

禁用lazy loading

_storeEntities.Configuration.LazyLoadingEnabled = false;

在构造函数中或要运行的查询之前。 或者只需删除virtual关键字。

您还可以禁用用于延迟加载的代理创建:

_storeEntities.Configuration.ProxyCreationEnabled = false;