6 c# entity-framework entity-framework-core .net-core asp.net-core
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;
Run Code Online (Sandbox Code Playgroud)
db.Configuration.ProxyCreationEnabled
整个错误信息:
错误 CS1061“ModelDBContext”不包含“Configuration”的定义,并且找不到接受“ModelDBContext”类型的第一个参数的可访问扩展方法“Configuration”(您是否缺少 using 指令或程序集引用?)
基于 Entity Framework Core 文档:https://learn.microsoft.com/en-us/ef/core/querying/lated-data,从 EF Core 2.1 开始,有一种方法可以在使用或不使用代理的情况下启用延迟加载。
1. 使用代理延迟加载:
A。确保您的导航属性定义为“虚拟”
b. 安装 Microsoft.EntityFrameworkCore.Proxies 包
C。通过调用 UseLazyLoadingProxies 启用它
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
=> optionsBuilder
.UseLazyLoadingProxies()
.UseSqlServer(myConnectionString);
Run Code Online (Sandbox Code Playgroud)
或者在使用 AddDbContext 时启用它
.AddDbContext<BloggingContext>(
b => b.UseLazyLoadingProxies()
.UseSqlServer(myConnectionString));
Run Code Online (Sandbox Code Playgroud)
2.无代理延迟加载:
A。将 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;
}
}
Run Code Online (Sandbox Code Playgroud)
默认情况下,EF Core 不会使用代理延迟加载,但如果您想使用代理,请遵循第一种方法。
| 归档时间: |
|
| 查看次数: |
4623 次 |
| 最近记录: |