EF Core中的.Configuration.ProxyCreationEnabled等价于什么?

时间:2019-03-19 06:33:46

标签: 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

整个

错误消息:

  

错误CS1061'ModelDBContext'不包含'Configuration'的定义,并且找不到可以接受的扩展方法'Configuration'接受类型为'ModelDBContext'的第一个参数(是否缺少using指令或程序集引用?)

1 个答案:

答案 0 :(得分:1)

基于EF Core 2.1的Entity Framework Core文档:https://docs.microsoft.com/en-us/ef/core/querying/related-data,有一种方法可以启用带或不带代理的延迟加载。

1。使用代理延迟加载:

a。确保将您的导航属性定义为“虚拟”

b。安装Microsoft.EntityFrameworkCore.Proxies包

c。通过调用UseLazyLoadingProxies启用它

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    => optionsBuilder
        .UseLazyLoadingProxies()
        .UseSqlServer(myConnectionString);

或在使用AddDbContext时启用它

.AddDbContext<BloggingContext>(
    b => b.UseLazyLoadingProxies()
          .UseSqlServer(myConnectionString));

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;
    }
}

默认情况下,EF Core不会对代理使用延迟加载,但是如果您想使用代理,请遵循第一种方法。

相关问题