none
Help with include vs load RRS feed

  • Question

  • we have some code that loops through and adds "includes" for all the related entities

    but -- if you have more than one child relation, the sql that is generated is very messy, with union alls 

    so -- we are trying to use "load" instead for any child relations after the first one

    it seemed to be working okay

    but there is a wierd side effect

    our relationship names are not unique, for example we have a Inspection relationship that is on several different entities

    once we do the load(), it populates all the levels, this is increasing the size of our result a lot

    for example

    Claim -> Inspection

    Claim -> Location

    Location -> Inspection

    When we load the Inspection, it is loading at both levels

    It is only running the sql once, which is good, but it is populating the entity at both levels

    Here is some example code

    // we did an include earlier to get the first child 
    entity = collection.AsNoTracking().First();
    
    // now we reattach it and get some others
    Type typeParameterType = typeof(T);
    
    DbContext.Set(typeParameterType).Attach(Convert.ChangeType(entity, typeParameterType));
    
    DbContext.Entry(Convert.ChangeType(entity, typeParameterType)).Collection(relation).Load();
    
    

    Wednesday, July 19, 2017 9:26 PM

All replies

  • Hi blue1000,

    >>It is only running the sql once, which is good, but it is populating the entity at both levels

    According to your description, it seems that you want to query Inspection records from database when you need to use it, Based on your code, it seems that you want to use Explicit Loading pattern, which could match your requirement.

    The following document, which introduce about Lazy, Eager, and Explicit Loading of Related Data for your reference.

    https://docs.microsoft.com/en-us/aspnet/mvc/overview/getting-started/getting-started-with-ef-using-mvc/reading-related-data-with-the-entity-framework-in-an-asp-net-mvc-application

    if you use Explicit Loading, you could refer to the following code.

    var entity = db.Claims.Find(1);
    // Load the Inspections related to a given Calim 
    db.Entry(entity).Collection("Inspections").Load();

    if I misunderstand your issue, please describe it in detailed and feel free let me know.

    Best regards,

    Cole Wu


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.


    Friday, July 21, 2017 8:34 AM
    Moderator