如何使用 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
中注册为:
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
使用延迟加载,如此处:
I'm trying to use lazy loading with Microsoft.EntityFrameworkCore.Proxies
as described here:
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.User
和 Session.User.Organization
默认为空.要加载它们,我必须执行诸如 context.All
之类的操作.我怎样才能避免这种情况?为什么 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 Core(和代理)版本:
2.1.0-preview2-final
推荐答案
在 Asp.net Core 2.1 中使用代理配置延迟加载的步骤
- 安装 Microsoft.EntityFrameworkCore.Proxies 包
- 启用延迟加载代理您可以通过调用 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屋!