如何让EF Core 2.1.0和代理进行延迟加载 [英] How to make lazy-loading work with EF Core 2.1.0 and proxies
问题描述
我有以下模型:
public class Session
{
public int SessionID { get; set; }
public int UserID { get; set; }
public virtual User User { get; set; }
}
public class User
{
public int UserID { get; set; }
public int OrganizationID { get; set; }
public virtual ICollection<Session> Sessions { get; set; }
public virtual Organization Organization { get; set; }
}
public class Organization
{
public int OrganizationID { get; set; }
public virtual ICollection<User> Users { get; set; }
}
在 DbContext $ c中注册的$ c>为:
modelBuilder.Entity<Session>(entity =>
{
entity.ToTable("sessions");
entity.Property(e => e.SessionID).HasColumnName("id");
entity.Property(e => e.UserID).HasColumnName("user_id");
entity.HasOne(e => e.User)
.WithMany(e => e.Sessions)
.HasForeignKey(e => e.UserID);
}
modelBuilder.Entity<User>(entity =>
{
entity.ToTable("users");
entity.Property(e => e.UserID).HasColumnName("id");
entity.Property(e => e.OrganizationID).HasColumnName("organization_id");
entity.HasOne(e => e.Organization)
.WithMany(e => e.Users)
.HasForeignKey(e => e.OrganizationID);
}
modelBuilder.Entity<Organization>(entity =>
{
entity.ToTable("organizations");
entity.Property(e => e.OrganizationID).HasColumnName("id");
}
我正在尝试对 Microsoft使用延迟加载.EntityFrameworkCore.Proxies
,如此处:
builder.Register(c =>
{
var optionsBuilder = new DbContextOptionsBuilder<Context>();
optionsBuilder
.UseLazyLoadingProxies()
/* more options */
;
var opts = optionsBuilder.Options;
return new Context(opts);
}).As<DbContext>().InstancePerLifetimeScope();
我正在使用 context.All< Session>
。但是, Session.User
和 Session.User.Organization
默认为空。要加载它们,我必须做类似 context.All< Session>()。Include(s => s.User).Include(s => s.User.Organization)
。我该如何避免呢?为什么 UseLazyLoadingProxies
不起作用?
I'm querying sessions using context.All<Session>
. However, Session.User
and Session.User.Organization
are null by default. To load them I have to do something like context.All<Session>().Include(s => s.User).Include(s => s.User.Organization)
. How can I avoid that? Why doesn't UseLazyLoadingProxies
work?
- .NET Core版本:
2.1.300-preview2-008533
- 目标:
netcoreapp2.1
- EF核心(和代理)版本:
2.1.0-preview2-final
- .NET Core version:
2.1.300-preview2-008533
- Target:
netcoreapp2.1
- EF Core (and Proxies) version:
2.1.0-preview2-final
推荐答案
在Asp.net Core 2.1中使用代理配置延迟加载的步骤
- 安装Microsoft.EntityFrameworkCore.Proxies软件包
- 启用LazyLoadingProxies
您可以通过以下方式启用它调用UseLazyLoadingProxies:
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
=> optionsBuilder
.UseLazyLoadingProxies()
.UseSqlServer(myConnectionString);
或者在使用AddDbContext时:
Or when using AddDbContext:
.AddDbContext<BloggingContext>(
b => b.UseLazyLoadingProxies()
.UseSqlServer(myConnectionString));
- 然后,EF Core将为任何对象启用延迟加载可以覆盖的导航属性,即它必须是虚拟的。
这篇关于如何让EF Core 2.1.0和代理进行延迟加载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!