【发布时间】:2020-06-16 08:55:25
【问题描述】:
我正在使用 EFCore 3.1.5,并且我有一个 DbContext,我希望能够在同一个控制器或服务中使用,无论是懒惰的还是急切的。但是,似乎我无法让它正确加载延迟。 Eager 似乎工作正常。
每当我做一些简单的事情时:
var users = await _lazyDbContext
.Users
.Take(10)
.ToListAsync();
每个User 上的每个导航属性都为空。但是,通过预先加载,它可以正常工作:
var users = await _dbContext
.Users
.Include(x => x.Contact)
.Take(10)
.ToListAsync();
Startup.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<LazyUserContext>((sp, opt) =>
{
var connectionString = "very secret";
opt.UseSqlServer(connectionString, x => x.CommandTimeout(300));
opt.UseLazyLoadingProxies();
});
services.AddDbContext<UserContext>((sp, opt) =>
{
var connectionString = "very secret";
opt.UseSqlServer(connectionString, x => x.CommandTimeout(300));
});
services.AddScoped<IUserContext, UserContext>();
services.AddScoped<ILazyUserContext, LazyUserContext>();
}
UserContext.cs
public interface IUserContext
{
DbSet<User> Users { get; set; }
DbSet<Contact> Contacts { get; set; }
}
public class UserContext : DbContext, IUserContext
{
public UserContext(DbContextOptions<UserContext> options) : base(options) {}
public DbSet<User> Users { get; set; }
public DbSet<Contact> Contacts { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Users>(e =>
{
e.HasOne(x => x.Contact).WithOne(x => x.User).HasForeignKey(x => x.ContactId);
}
}
}
LazyUserContext.cs
public interface ILazyUserContext : IContext {}
public class LazyUserContext : UserContext, ILazyUserContext
{
public LazyUserContext(DbContextOptions<UserContext> options) : base(options) {}
}
这可能是什么问题?我试图在我的控制器/服务中对接口和类进行 IoC。我尝试过使用和不使用services.AddScoped<>()。
我想要的只是能够使用惰性 dbContext 或渴望 dbContext,我希望默认使用渴望的 dbContext。
【问题讨论】:
-
这可能听起来很愚蠢,但请尝试在
opt.UseSqlServer(connectionString, x => x.CommandTimeout(300)); opt.UseLazyLoadingProxies();左右切换这些opt.UseLazyLoadingProxies(); opt.UseSqlServer(connectionString, x => x.CommandTimeout(300)); -
@Seabizkit 不幸的是,这不会有所作为。我知道延迟加载是有效的,因为如果我简单地删除所有
LazyContext的东西,那么只有 1 个 DbContext,延迟加载就可以完美地工作。 -
好吧,嗯,我在想你是如何注册它的......你需要通过获取实例
services.AddScoped<DbContext>(provider => provider.GetService<ParadoxCoreContext>());来重用定义的方式,这是我自己的项目,但需要满足你的需求......试试看 -
本页docs.microsoft.com/en-us/dotnet/api/… 提到可能需要致电
services.AddEntityFrameworkProxies() -
@MortenMoulder 这就是我的意思
services.AddScoped<ILazyUserContext, LazyUserContext>((provider => provider.GetService<LazyUserContext>() );你需要告诉你的范围版本中的寄存器使用已经定义的结构,你已经指定了 UseLazyLoadingProxies,这是我的理解,否则@ 987654335@知道如何构造LazyUserContext...
标签: c# entity-framework entity-framework-core ef-core-3.1