Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
748 views
in Technique[技术] by (71.8m points)

c# - What is the equivalent of .Configuration.ProxyCreationEnabled in EF Core?

What is the equivalent of .Configuration in Entity Framework Core? Receiving error below

Code Examples:

        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 Messages throughout:

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?)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Based on Entity Framework Core docs: https://docs.microsoft.com/en-us/ef/core/querying/related-data, from EF Core 2.1, there is a way to enable Lazy Loading with or without proxy.

1. Lazy Loading with Proxy:

a. Make sure your navigation property are defined as "virtual"

b. Install the Microsoft.EntityFrameworkCore.Proxies package

c. Enable it with a call to UseLazyLoadingProxies

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

Or enable it when using AddDbContext

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

2. Lazy Loading without Proxy:

a. Injecting the ILazyLoader service into an entity, as described in Entity Type Constructors. For example:

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

By default, EF Core won't use lazy load with proxy, but if you want to use proxy, please follow 1st approach.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...