Let's say I have the following 2 classes that will represent a relationship between 2 DB Tables (created using EF Core Migrations):
public class Author
{
public int Id { get; set; }
public string Name { get; set; }
public Book Book { get; set; }
}
public class Book
{
public int Id { get; set; }
public String name { get; set; }
public string Genre { get; set; }
}
These 2 classes are added in as a DbSet
in my ApplicationDbContext
class.
When I retrieve the Author
record, I want the Book
object to also be populated info. It seems I have to retrieve it in the following way:
return _context.Author.Include(x => x.Book).ToList();
If I had a dozen of different objects in the Author
class does that mean I have to chain the .Include()
method calls for each object? Is there a catch-all method that will tell me to populate all of the objects inside the Author
class? Something like .IncludeAll()
perhaps?
You can use lazy loading enabled on your EF core. This way you don't need to include it every time.
Basically you need to add virtual keyword to your book entity:
public class Author{
public int Id {get; set;}
public string Name {get; set; }
public virtual Book Book {get; set; }
}
public class Book {
public int Id {get; set;}
public String name {get; set;}
public string Genre {get; set; }
}
Then you need to enable lazy loading by installing the Microsoft.EntityFrameworkCore.Proxies package and enabling it with a call to UseLazyLoadingProxies. For example: In you startup.cs class modify the dbcontext as below
services.AddDbContext<BloggingContext>(
b => b.UseLazyLoadingProxies()
.UseSqlServer(myConnectionString));
Please refer the following link to understand how lazy loading works https://docs.microsoft.com/en-us/ef/core/querying/related-data