0

I have an auto generated class (Orders class) which references other objects. What i'm trying to accomplish is get an order using the order id and the user related to that order.

However when loading the object it is taking 2 seconds to load it. I looked at the object and EF is populating the list of all the dependent objects (Language, country, customer user).

How do i get only specific object like only the order properties and the user object ? I tried to accomplish that using the below code but it is loading all the objects.

//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 Answers 2

2

You should disable Lazy loading in configuration

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

Or only during your call

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

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

Here is the MSDN article for every type of loading

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

Sign up to request clarification or add additional context in comments.

Comments

2

Disable lazy loading:

_storeEntities.Configuration.LazyLoadingEnabled = false;

In constructor or before the query you want to run. Or just remove virtual keyword.

Also you can disable proxy creation which is used for lazy loading:

_storeEntities.Configuration.ProxyCreationEnabled = false;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.