Entity Framework Core 中 .Configuration 的等价物是什么?收到以下错误
代码示例:
List<DocumentStatus> documentStatuses;
using (var db = new ModelDBContext())
{
db.Configuration.ProxyCreationEnabled = false;
documentStatuses = db.DocumentStatus.ToList();
}
using (var db = new ModelDBContext())
{
db.Configuration.ProxyCreationEnabled = false;
//Expression<Func<Owner, bool>> predicate = query => true;
db.Configuration.ProxyCreationEnabled
整个错误消息:
Error CS1061 'ModelDBContext' does not contain a definition for 'Configuration' and no accessible extension method 'Configuration' accepting a first argument of type 'ModelDBContext' could be found (are you missing a using directive or an assembly reference?)
最佳答案
基于 Entity Framework Core 文档:https://docs.microsoft.com/en-us/ef/core/querying/related-data ,从 EF Core 2.1 开始,有一种方法可以在有或没有代理的情况下启用延迟加载。
1. 代理延迟加载:
一种。确保您的导航属性被定义为“虚拟”
湾。安装 Microsoft.EntityFrameworkCore.Proxies 包
C。通过调用 UseLazyLoadingProxies 启用它
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
=> optionsBuilder
.UseLazyLoadingProxies()
.UseSqlServer(myConnectionString);
或者在使用 AddDbContext 时启用它
.AddDbContext<BloggingContext>(
b => b.UseLazyLoadingProxies()
.UseSqlServer(myConnectionString));
2. 无代理延迟加载:
一种。将 ILazyLoader 服务注入(inject)实体中,如实体类型构造函数中所述。例如:
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;
}
}
默认情况下,EF Core 不会使用代理的延迟加载,但如果您想使用代理,请遵循第一种方法。
关于c# - EF Core 中 .Configuration.ProxyCreationEnabled 的等价物是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55234943/