Entity Framework 6: related objects are automatically added to the parent, even though lazy loading is disabled

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 a list of SalesSubCategories without loading the SalesCategory object.

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

Linked object not loaded

This method returns a list of SalesSubCategories 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;
} 

Linked object uploaded

MD_Context is configured to disable lazy loading:

Configuration.LazyLoadingEnabled = false;

Is this the expected behavior? My preferred result: DO NOT have pre-loaded SalesCategory object objects.

Thank.

+4
source share
2 answers

Yes, this is the expected behavior.

, , , .

, . , entityframework .

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

, ​​ , , LazyLoadingEnabled . , , SalesCategory, , LazyLoadingEnabled , , ,

0

Source: https://habr.com/ru/post/1655665/


All Articles