Load child entity on the fetch of the Parent entity EFCore

前端 未结 3 1023
感情败类
感情败类 2021-01-22 16:50

I have the below model. What is the better way to load the parent entity with child entity at the time of fetching from the DB with find method?

Parent Entity:

相关标签:
3条回答
  • 2021-01-22 17:03

    In EF, there is a concept called Eager Loading using .Include.

    MS Docs - Loading Related Data - EF Core

    .NET Fiddle

    using MyContext context = new MyContext();
    
    IList<Client> clients =
        context.Clients
            .Include(c => c.Address)
            .Where(c => c.LastName == "patel")
            .ToList();
    
    0 讨论(0)
  • 2021-01-22 17:15

    As you said:

    Notes: As of now, if I used the Include(i => i.Address) then, and then, only I am able to load the child entity.

    Yes! this is the best way to load related data in EF Core.

    You further said:

    I already use the Include but is there any other option exist to load child entity if I get the parent entity.

    Yes! There is! That is called Lazy loading. To enable lazy loading you have to make the navigation property virtual as follows:

    public class Client
    {
        public int Id { get; set; }
    
        public string LastName { get; set; }
    
        public string Gender { get; set; }
    
        public DateTime DateOfBirth { get; set; }
    
        public virtual Address Address { get; set; } // <-- Here it is
    }
    

    And you have to register your DbConext as follows:

    services.AddDbContext<BloggingContext>(
        b => b.UseLazyLoadingProxies() // <-- Here is it is
              .UseSqlServer(myConnectionString));
    

    UseLazyLoadingProxies() method is available in the Microsoft.EntityFrameworkCore.Proxies nuget package.

    Note: You cannot disable lazy loading for a certain query. So using Eager loading is the best way to load related data in EF Core.

    0 讨论(0)
  • 2021-01-22 17:25

    You can use Include()

    Linq query

    using (var context = new DBEntities())
    {
       var result = (from c in context.Client.Include("Address")
                where c.IsActive
                select c).ToList();
    }
    

    Lambda Expression

    using (var context = new DBEntities())
    {
       var result = context.Client.Include(p => p.Address).Where(c => c.IsActive).ToList();
    }
    
    0 讨论(0)
提交回复
热议问题