c# - EF Core 中 .Configuration.ProxyCreationEnabled 的等价物是什么?

标签 c# entity-framework asp.net-core .net-core entity-framework-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;

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/

相关文章:

c# - Async/Await 和 Task<T> 不返回数据

c# - Telnet 阻塞 C# TCP 服务器

.net - 实现自定义 ValidationAttribute 时应该覆盖哪个 IsValid 方法

c# - 在 asp .net core 3 中使用进程内托管设置请求超时

c# - 从 C# 或 .cmd 提示符执行 .sh

c# 引用 a 使用继承自 c 的 b

c# - 带有 Id 的通用类 C#

c# - Fluent Api中的等价显示Annotation是什么?

c# - 从方法外部获取到操作的路径

c# - 在 .net core 的单元测试中使用和注入(inject) appsettings.json