简体   繁体   中英

linq - Best way to get records from linked table

I'm new to entity framework and i have following database structure.

D b

i'm trying to get relevant template for test.

what i have tried so far is as follows:

var val = context.TeamTest
     .Where(x => x.Tests_Id == 47)
     .Select(x => x.Team.Profile.ProfileSelections);

Q1 : why can't i get .Select(x => x.Team.Profile.ProfileSelections.Templates);

I tried this way as well.

List<TeamTaskTemplate> templates = (from candidate in context.TeamTest
                                    join team in context.Teams  
                                    on candidate.Team_ID equals team.Team_ID
                                    join profile in context.Profiles
                                    on team.TeamTaskProfileID equals profile.TeamTaskProfileID
                                    join selectProf in context.ProfileSelections
                                    on profile.TeamTaskProfileID equals selectProf.TeamTaskProfileID
                                    join templ in context.Templates 
                                    on selectProf.TeamTaskTemplateID equals templ.TeamTaskTemplateID
                                    where candidate.Test_Id == 47
                                    select templ).ToList();

Q2 : What is the best way to get records from above 2 methods ?

Q3 in general what is the best way to get records ? ( directly using context object as i mention 1 or use join queries mentioned in 2 ?

Q1: You should switch on LazyLoading:

context.Configuration.LazyLoadingEnabled = true;

And check that Team, Profile, ProfileSelections and Templates properties have virtual annotation.

Q2, Q3: First method is very simple and clear for understanding, but second one can be more effective.

Q1 If you mapping be correctly Info

var val = context.TeamTest.Include("Team.Profile.ProfileSelection.Template")
     .Where(x => x.Tests_Id == 47).ToList();

For me this is the best way because get and set only the data that you needs

Loading Related Entities

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM