EF 6 filtering child collections

后端 未结 3 1241
臣服心动
臣服心动 2021-01-04 11:46

I\'m trying to migrate old project from Linq2Sql to EF6 and I got following issue.

This project is multilingual (i.e. all texts have more than 1 translation) and I h

3条回答
  •  孤独总比滥情好
    2021-01-04 12:21

    If you want to perform the filtering in the query to the database then (as of EF6) you have to use the Query method:

    The Query method provides access to the underlying query that the Entity Framework will use when loading related entities. You can then use LINQ to apply filters to the query before executing it with a call to a LINQ extension method such as ToList, Load, etc.

    using (var context = new BloggingContext()) 
    { 
      var blog = context.Blogs.Find(1); 
    
      // Load the posts with the 'entity-framework' tag related to a given blog 
      context.Entry(blog) 
        .Collection(b => b.Posts) 
        .Query() 
        .Where(p => p.Tags.Contains("entity-framework") 
        .Load(); 
    
       // Load the posts with the 'entity-framework' tag related to a given blog  
       // using a string to specify the relationship  
       context.Entry(blog) 
         .Collection("Posts") 
         .Query() 
         .Where(p => p.Tags.Contains("entity-framework") 
         .Load(); 
    }
    

    However, the obvious drawback is that you have to do this per entry and each Load call executes a query against the database.

    Unless it's a hard requisite for you I would opt for just loading all the localizations and simply filter in memory to use the selected language one. I'm pretty sure the performance won't be an issue.

提交回复
热议问题