Lazy load in Web API Core 2.2

…衆ロ難τιáo~ 提交于 2019-12-07 17:09:12

问题


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.



来源:https://stackoverflow.com/questions/54150622/lazy-load-in-web-api-core-2-2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!