Web API Core 2.2中的延迟加载 [英] Lazy load in Web API Core 2.2

查看:69
本文介绍了Web API Core 2.2中的延迟加载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在延迟加载方面遇到了问题.我有以下dbcontext.

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

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

我已启用延迟加载.

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

我的理解是,如果启用了延迟加载,则不应显示测试1.1和测试2.1".如果我做错了任何事情,请告诉我.

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.

推荐答案

延迟加载将仅在访问它们时获取值.吐出JSON时,将访问属性,并且EF Core作为单独的查询来检索值.因此,不建议在ASP.NET Core中使用延迟加载.

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.

这篇关于Web API Core 2.2中的延迟加载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆