当前位置: 移动技术网 > IT编程>开发语言>.net > EF Core 通过延迟加载获取导航属性数据

EF Core 通过延迟加载获取导航属性数据

2019年09月11日  | 移动技术网IT编程  | 我要评论

崔亚光,英雄无敌大军在异界,双一流名单发布

ef 6及以前的版本是默认支持延迟加载(lazy loading)的,早期的ef core中并不支持,必须使用include方法来支持导航属性的数据加载。
当然在ef core 2.1及之后版本中已经引入了延迟加载功能,详细实现原理可以查看官网()。
下面记录一下,分别使用includelazy loading来支持导航属性的数据加载。

entity数据库实体

简单的一个多对多关系,分别对应数据库中的3张表。学生和学校之间通过stuschreg关联,相互之间可以通过导航属性获取数据。

public class student
{
    public int id { get; set; }
    public string name { get; set; }
    public virtual ilist<stuschreg> regs { get; set; }
}

public class school
{
    public int id { get; set; }
    public string name { get; set; }
    public virtual ilist<stuschreg> regs { get; set; }
}
public class stuschreg
{
    public int id { get; set; }
    public int stdid { get; set; }
    [foreignkey("stdid")]
    public virtual student student { get; set; }

    public int schid { get; set; }
    [foreignkey("schid")]
    public virtual school school { get; set; }
}

通过导航属性获取数据

数据查询需求:通过学校id获取学校中所有学生的信息

[httpget]
[httppost]
public async task<jsonresult> test(int id)
{
    return await task.run(() =>
    {
        var school = dbcontext.school.find(id);
        var list = school.regs.select(d => new { d.student.id, d.student.name });
        return success(list);
    });
}

这种情况下school.regs会报错(未将对象引用到实例),断点查看会发现值为null。
解决方法
1.通过include直接加载导航属性
将获取school的语句修改一下,可以正常获取到数据。

var school = dbcontext.school
    .include(d => d.regs)
        .theninclude(d => d.student)
    .firstordefault(d => d.id == id);

2.开启ef core的延迟加载功能
使用延迟加载的最简单方式是安装 microsoft.entityframeworkcore.proxies 包,并通过调用 uselazyloadingproxies 来启用。
例如:在dbcontext的onconfiguring方法中启用

protected override void onconfiguring(dbcontextoptionsbuilder optionsbuilder)
{
    optionsbuilder
        .uselazyloadingproxies()
        .usesqlserver(myconnectionstring);
}

或在使用adddbcontext时启用

services.adddbcontext<bloggingcontext>(
    b => b.uselazyloadingproxies()
          .usesqlserver(myconnectionstring));

ef core会为可重写的任何导航属性(必须是 virtual 且在可被继承的类上)启用延迟加载。
这时候还原为最开始的调用方式,也可以正常获取到导航属性的数据了。

var school = dbcontext.school.find(id);

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网