简体   繁体   中英

How to load specific objects in entity framework

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; }
     }

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

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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