Manually select related table data (SELECT N + 1 problem) LINQ to SQL

前端 未结 2 795
别跟我提以往
别跟我提以往 2021-01-18 18:44

Database example:

Image - ImageTag - Tag

Images can have multiple tags. The relationships are set up fine and stuff but I am running into pe

相关标签:
2条回答
  • 2021-01-18 18:52

    You can use the DataLoadOptions class to load related objects with a query.

    DataLoadOptions dlo = new DataLoadOptions();
    
    dlo.LoadWith<Image>(image => image.ImageTags);
    dlo.LoadWith<ImageTag>(imageTag => imageTag.Tags);
    
    context.DataLoadOptions = dlo;
    

    Just to mention - this is called the "SELECT N + 1 problem".

    UPDATE

    I am usually using LINQ to Entities and have not much experience with LINQ to SQL. It might be required to disable DeferredLoadingEnabled explicitly, too.

    context.DeferredLoadingEnabled = false;
    
    0 讨论(0)
  • 2021-01-18 19:05

    why not try something like:

    return
            from i in qry
            from iTags in i.ImageTags
            where tags.Contains(iTags.Tag)
            select new { TagName = i.Tag.name };
    

    That will return a Collection with only the Tag Names. I hope I'm understanding your question properly here. Hope it helps

    0 讨论(0)
提交回复
热议问题