Gmd3 Gmd3 - 2 months ago 19
C# Question

Entity Framework 6: related entities auto added to parent entity despite lazy loading being turned off

I have 2 classes, SalesSubCategory and SalesCategory:

[Table("SALES.SubCategory")]
public class SalesSubCategory
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int ID { get; set; }

public int CategoryID { get; set; }

public string Name { get; set; }

[ForeignKey("CategoryID")]
public SalesCategory SalesCategory { get; set; }
}

[Table("SALES.Category")]
public class SalesCategory
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int ID { get; set; }

public string Name { get; set; }
}


This Method returns SalesSubCategories List WITHOUT the SalesCategory Object loaded

public class TestController : Controller
{
private readonly MD_Context _context;

public TestController(MD_Context context)
{
_context = context;
}
public async Task<List<SalesSubCategory>> NoRelated()
{
var subCategories = await _context.SalesSubCategories.ToListAsync();
return subCategories;
}


Related Entity not Loaded

This Method returns SalesSubCategories List WITH the SalesCategory Object loaded

public async Task<List<SalesSubCategory>> Related()
{
var subCategories = await _context.SalesSubCategories.ToListAsync();
var categories = await _context.SalesCategories.ToListAsync();
return subCategories;
}


Related Entity loaded

MD_Context is configured to have lazy loading disabled:

Configuration.LazyLoadingEnabled = false;


Is this expected behavior? My preferred result is to NOT have the SalesCategory object entities pre-loaded.

Thank you.

Answer

Yes this is expected behavior.

When loading entities from a context, the entities in play get attached in order to keep track on any modification on them, that is way, you get the results due to previous loading.

You can solve it by requesting the query to execute in a non tracking fashion. Which will not make entityframework associate it with your new query.

var subCategories = await _context.SalesSubCategories.ToListAsync();
var categories = await _context.SalesCategories.AsNoTracking().ToListAsync();