延迟加载EF Core 2.1无法使用Identity?

时间:2018-06-06 14:06:23

标签: c# lazy-loading ef-core-2.1

我按照这里的例子

https://docs.microsoft.com/en-us/ef/core/querying/related-data#lazy-loading

我的两个课程看起来像这样

  public class RefMedSchool
{
    public int Id { get; set; }
    public string Code { get; set; }
    public string Name { get; set; }


    public virtual ICollection<ApplicationUser> ApplicationUser { get; set; }
}


 public class ApplicationUser : IdentityUser
{
    public string UserFirstName { get; set; }
    public string UserLastName { get; set; }
    public bool MustChangePassword { get; set; }


    public int? MedicalSpecialtyId { get; set; }
    [ForeignKey("RefMedicalSpecialtyForeignKey")]
    public RefMedicalSpecialty RefMedicalSpecialty { get; set; }


    public int RefMedSchoolId { get; set; }
    public virtual RefMedSchool RefMedSchool { get; set; }


    public UserProfileData UserProfileData { get; set; }


    public ICollection<UserFeedback> UserFeedbacks { get; set; }


    public ICollection<UserAction> UserActions { get; set; }


    public ICollection<UserProgram> UserPrograms { get; set; }
}

但是当尝试创建数据库时,我收到以下错误。怎么了 ?根据需要,属性是虚拟的。

  

System.InvalidOperationException:&#39;导航属性&#39; RefMedicalSpecialty&#39;在实体类型&#39; ApplicationUser&#39;不是虚拟的。 UseLazyLoadingProxies要求所有实体类型都是公共的,未密封的,具有虚拟导航属性,并且具有公共或受保护的构造函数。&#39;

2 个答案:

答案 0 :(得分:3)

Entity Framework Core 2.1引入了延迟加载。它需要所有导航属性为虚拟,如问题Lazy-loading proxies: allow entity types/navigations to be specified中所述:

  

目前,当使用延迟加载代理时,模型中的每个实体类型都必须适合代理,并且所有导航必须是虚拟的。这个问题是关于允许某些实体类型/导航延迟加载而其他实体类型/导航不是。

问题仍然存在且没有解决方案,因此您的理想方案仍然不受支持。

正如例外情况告诉你的那样:

  

UseLazyLoadingProxies要求所有实体类型都是公共的,未密封的,具有虚拟导航属性,并且具有公共或受保护的构造函数。

因此,将所有导航属性(即引用其他实体的属性)更改为virtual

或按照Lazy-loading without proxies中的说明使用ILazyLoader

public class Blog
{
    private ICollection<Post> _posts;

    public Blog()
    {
    }

    private Blog(ILazyLoader lazyLoader)
    {
        LazyLoader = lazyLoader;
    }

    private ILazyLoader LazyLoader { get; set; }

    public int Id { get; set; }
    public string Name { get; set; }

    public ICollection<Post> Posts
    {
        get => LazyLoader?.Load(this, ref _posts);
        set => _posts = value;
    }
}

答案 1 :(得分:-2)

将您的财产更改为&#34;虚拟&#34;属性。

相关问题