Lazy load in Web API Core 2.2

2020-07-23 06:50发布

问题:

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:

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.