entity frameowrk

usha 100 Reputation points
2023-11-24T16:32:35.55+00:00

hi iam using dotnet 6 iam new to dotnet can any one tell me how to enable lazyloading in dotnet6 s currently its not working

Entity Framework Core
Entity Framework Core
A lightweight, extensible, open-source, and cross-platform version of the Entity Framework data access technology.
724 questions
0 comments No comments
{count} votes

Accepted answer
  1. AgaveJoe 1,495 Reputation points
    2023-11-24T21:32:38.6933333+00:00

    See the official documentation which illustrates how to enable lazy loading. If you followed the documentation and are still having trouble then share enough code to reproduce the problem.

    Lazy Loading of Related Data

    dotnet add package Microsoft.EntityFrameworkCore.Proxies --version 8.0.0
    
    .AddDbContext<BloggingContext>(
        b => b.UseLazyLoadingProxies()
              .UseSqlServer(myConnectionString));
    
    2 people found this answer helpful.

1 additional answer

Sort by: Most helpful
  1. Kesava Subhash Gullapudi 30 Reputation points
    2023-11-28T13:10:08.81+00:00

    Actually Lazy loading was Cause an effect to an application .. but here i will show you an scenario how to gone through it ...!

    
    
    public class Blog
    {
        public int BlogId { get; set; }
        public string Name { get; set; }
    
        // Lazy-loaded collection of posts
        public virtual ICollection<Post> Posts { get; set; }
    }
    
    public class Post
    {
        public int PostId { get; set; }
        public string Title { get; set; }
        public string Content { get; set; }
    }
    
    public class BlogContext : DbContext
    {
        public DbSet<Blog> Blogs { get; set; }
        public DbSet<Post> Posts { get; set; }
    }
    
    class Program
    {
        static void Main()
        {
            using (var context = new BlogContext())
            {
                // Assume there is a blog with BlogId = 1 in the database
                var blog = context.Blogs.Find(1);
    
                // At this point, the blog's posts are not loaded yet
    
                // Accessing the Posts property triggers lazy loading, and the posts are loaded from the database
                foreach (var post in blog.Posts)
                {
                    Console.WriteLine($"Title: {post.Title}, Content: {post.Content}");
                }
            }
        }
    }
    
    

    0 comments No comments