简体   繁体   中英

Entity Framework proper use of joining tables?

I have the syntax below. I have set up sql constraints (ie foreign key relationships in the data model, etc..). I am wondering how I can write this statement using a lambda expression. Is it possible? I have read articles about eager loading, but not sure how that would apply and if I can write the query more concise?

var nominations = from n in ctx.Nominations
                              join c in ctx.Nominees
                              on n.NominationId equals c.NominationId
                              where c.NomineeADUserName == UserName
                              select n;

You can write the same query using Method syntax as follows:

ctx.Nominations.Join(ctx.Nominees, 
                     n=>n.NominationId, 
                     c=>c.NominationId, 
                     (n,c)=>new {c, n})
               .Where(x=>x.c.NomineeADUserName == Username)
               .Select(x.n);

I think its important to make it readable rather than concise. Your version is more readable.

Also whether you write method syntax or query syntax, the query will be evaluated in lazy fashion. If you want you can force eager loading by calling ToList() at the end of either query.

If you want to also load the navigation properties (related entities) then you have to call the Include method EntitySet before making it part of query

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