Home > Net >  Retrieve from DB and Include Multiple ICollections
Retrieve from DB and Include Multiple ICollections

Time:12-26

I'm working with EF6. I have a module with multiple ICollections. My solution to retrieve the lists of objects is similar but I find it dumb, as I need to rewrite this on all the pages where I need IEnumerable<BookModel> GetAllBook.

 IEnumerable<BookModel> GetAllBook = DBContext.BookModels.Include(x => x.AssociatedNames).Include(e => e.BlogModel);

I read several topics on this but these stood out. From what I understood, the answer is written in the DbContext.cs with the DbSets. But does the BookModule have a complete list of example authors? Without the need of including another time?

Include several references

I also read Why does EF Core One-to-Many relationship collection return null?

public class BookModel
{
    [Key]
    public int BookModelID{ get; set; }
    public virtual ICollection<AssociatedNames>? AssociatedNames { get; set; }
    public virtual List<BookModel>? relatedSeries { get; set; }
    public virtual List<BookModel>? RecommendedBookModels { get; set; }
    public virtual ICollection<AuthorModel>? Authormodels { get; set; }
    public virtual ICollection<ArtistModel>? ArtistModels { get; set; }
    public virtual ICollection<VoiceActorModel>? VoiceActors { get; set; }
    public virtual ICollection<GenresModel>? GenresModels { get; set; }
    public virtual ICollection<TagModel>? TagsModels { get; set; }
}

My question is there a way for my bookModel have the complete lists of objects without needing to use Include again, and again.

Best regards

CodePudding user response:

What you need in this cas is the AutoInclude feature introduced with EF6 , so You will have to go into the OnModelCreating Method and add the following lines ( you update that to your use case , depends on which related entities you want to be autoIncluded ):

    modelBuilder.Entity<BookModel>().Navigation(e => e.Authormodels).AutoInclude();
    modelBuilder.Entity<BookModel>().Navigation(e => e.Artistmodels).AutoInclude();

and if , for a specific cas you need only the books , and you want to get rid of the autoIncludes , then us can use the IgnoreAutoIncludes feature like below :

    var books = context.BookModels.IgnoreAutoIncludes().ToList();

Fore more details about this you can look up this documentation or this video

  • Related