Lazy load in Web API Core 2.2

c# entity-framework-core lazy-loading

Question

I am having issues with the lazy loading. I have the following dbcontext.

public virtual DbSet<AccountGroupMst> AccountGroupMst {get; set;}

I have enabled the lazy loading.

services.AddDbContext<DBContext>(x => 
                x.UseSqlServer(Configuration.GetConnectionString("Test"))
                .UseLazyLoadingProxies());

Model, I have virtual and it is a self referencing table.

public class AccountGroupMst
{
    [Key]
    [Required]
    public int AccountGroupId { get; set; }

    [MaxLength(255)]
    [StringLength(255)]
    [Required]
    public string AccountGroupName { get; set; }

    [ForeignKey("ParentAccountGroupId")]
    public  int? ParentAccountGroupId { get; set; }

    public virtual AccountGroupMst ParentGroup { get; set; }
}

The problem I have is, the Entity framework returns all the children.

{
    "data": {
        "0": {
            "parentGroup": {
                "parentGroup": {
                    "parentGroup": null,
                    "accountGroupId": 1,
                    "name": "Test 2.1",
                    "parentAccountGroupId": null
                },
                "accountGroupId": 5,
                "name": "Test 1.1",
                "parentAccountGroupId": 1
            },
            "accountGroupId": 18,
            "name": "Test",
            "parentAccountGroupId": 5
        }
    }
}

My understanding is if lazy load enabled, it is not supposed to display the 'Test 1.1 and Test 2.1'. Please let me know if I am making anything wrong.

1
3
1/12/2019 7:35:20 PM

Accepted Answer

Lazy loading will only get the values when they are accessed. When spitting out the JSON, the properties are accessed and the values are retrieved by EF Core as a separate query. Hence, it's not recommended to use lazy loading with ASP.NET Core.

3
1/12/2019 7:36:29 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow