2016-07-18 33 views
0

我有一個引用其他對象的自動生成的類(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

你應該只在您的通話中配置禁用延遲加載

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

2

禁用lazy loading

_storeEntities.Configuration.LazyLoadingEnabled = false; 

在構造函數或要運行查詢之前。 或者只是刪除virtual關鍵字。

您也可以禁用代理創建它用於延遲加載:

_storeEntities.Configuration.ProxyCreationEnabled = false;