I am learning EF. While practicing I noticed a strange behavior for Lazy Loading.
I read, Lazy loading is enabled by default and can work only if navigation properties are marked virtual along with LazyLoadingEnabled = ture in context's configuration.
So, I decided to turn off lazy loading by setting the switch to off i.e., LazyLoadingEnabled = false.
Here is the code that tried to access the dbset after then:
if (context == null)
context = new InventoryEntities(".");
context.Configuration.LazyLoadingEnabled = false;
List<STOCK_ITEM_GROUPS> res = (from groups in context.STOCK_ITEM_GROUPS
orderby groups.name
select groups).ToList<STOCK_ITEM_GROUPS>();
string msg = "";
foreach (var groups in res)
msg += "Name: " + groups.name + "\tParent Name: " + (groups.STOCK_ITEM_GROUPS2 == null ? "none" : groups.STOCK_ITEM_GROUPS2.name) + Environment.NewLine;
Console.WriteLine(msg);
Below is the dbset generated for STOCK_ITEM_GROUPS:
public partial class STOCK_ITEM_GROUPS
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public STOCK_ITEM_GROUPS()
{
this.STOCK_ITEM_GROUPS1 = new HashSet<STOCK_ITEM_GROUPS>();
this.STOCK_ITEM_MASTER = new HashSet<STOCK_ITEM_MASTER>();
}
public short id { get; set; }
public string name { get; set; }
public Nullable<short> idParent { get; set; }
public bool itemAddable { get; set; }
public bool isactive { get; set; }
public System.DateTime active_timestamp { get; set; }
public Nullable<System.DateTime> deactivation_timestamp { get; set; }
public byte[] rv { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<STOCK_ITEM_GROUPS> STOCK_ITEM_GROUPS1 { get; set; }
public virtual STOCK_ITEM_GROUPS STOCK_ITEM_GROUPS2 { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<STOCK_ITEM_MASTER> STOCK_ITEM_MASTER { get; set; }
}
Now, ideally I should not receive data for navigation property
public virtual STOCK_ITEM_GROUPS STOCK_ITEM_GROUPS2 { get; set; }
, since, lazy loading is not enabled. But, I am receiving the related data!
I tried turning lazy loading off in the context's constructor as well but no help.
I might be missing any conceptual thing or there is something else I dont really know.
Looking at debugger for queries generated, I find only one query that looks for all the data from database.
thus, there are not multiple queries too but there is the related data. I dont understand where I am going wrong.
What I have tried:
I tried the same with Load() method on DbSet, it also returns same result as ToList() returns.
Searched on google but found only 1 comment, which is not really the condition I am in, here is the link for that:
c# - Entity Framework - Lazy Loading working even with ToList() - Stack Overflow[
^]