简体   繁体   English

实体框架正确使用联接表?

[英]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..). 我已经设置了sql约束(即数据模型中的外键关系等)。 I am wondering how I can write this statement using a lambda expression. 我想知道如何使用lambda表达式编写此语句。 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: 您可以使用Method语法编写相同的查询,如下所示:

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. 如果需要,可以通过在任一查询的末尾调用ToList()来强制进行急切加载。

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 如果您还希望加载导航属性(相关实体),则必须在使其成为查询的一部分之前调用Include方法EntitySet

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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