Linq如何编写JOIN
Linq to EF,我使用的是 asp.net 4、EF 4 和 C#。
这是我想出的两种查询数据的方法。方式A和C工作正常。然而,B 需要实现额外的 WHERE 语句(如“where c.ModeContent == “NA”)。
我的问题是:
- 关于这种连接(我认为是外连接),就性能而言最好的方法是什么
- ?您向我展示了一些在 B 中实现附加 WHERE 语句的代码吗?
- 有什么方法可以改进此代码吗?
谢谢您的时间!
// A
var queryContents = from c in context.CmsContents
where c.ModeContent == "NA" &&
!(from o in context.CmsContentsAssignedToes select o.ContentId)
.Contains(c.ContentId)
select c;
// B - I need to implent where c.ModeContent == "NA"
var result01 = from c in context.CmsContents
join d in context.CmsContentsAssignedToes on c.ContentId equals d.ContentId into g
where !g.Any()
select c;
// C
var result02 = context.CmsContents.Where(x => x.ModeContent == "NA").Where(item1 => context.CmsContentsAssignedToes.All(item2 => item1.ContentId != item2.ContentId));
Linq to EF, I'm using asp.net 4, EF 4 and C#.
Here are two ways I came up with to query my data. Ways A and C are working fine. B however needs to implement and additional WHERE statement (as "where c.ModeContent == "NA").
My question is:
- Regarding this kind of join (outer join, I suppose) what is the best approach in term of performance?
- Could you show me some code to implement additional WHERE statement in B?
- Any way to improve this code?
Thanks for your time! :-)
// A
var queryContents = from c in context.CmsContents
where c.ModeContent == "NA" &&
!(from o in context.CmsContentsAssignedToes select o.ContentId)
.Contains(c.ContentId)
select c;
// B - I need to implent where c.ModeContent == "NA"
var result01 = from c in context.CmsContents
join d in context.CmsContentsAssignedToes on c.ContentId equals d.ContentId into g
where !g.Any()
select c;
// C
var result02 = context.CmsContents.Where(x => x.ModeContent == "NA").Where(item1 => context.CmsContentsAssignedToes.All(item2 => item1.ContentId != item2.ContentId));
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
对于查询 B,您可以应用这样的条件:
Regarding query B you can apply the condition like this:
如果您使用您的关联属性而不是
join
:我猜测
CmsContent
上的导航到CmsContentsAssignedToes 称为
AssignedToes
。如果它实际上被称为其他名称,请更改我的查询中的名称。这个查询可以大声读出,您确切知道它的含义。您必须考虑的
join
版本。Your query will be far more readable and maintainable (and perform at least as well) if you use your association properties instead of
join
:I'm guessing that the navigation on
CmsContent
toCmsContentsAssignedToes
is calledAssignedToes
. Change the name in my query if it's actually called something else.This query can be read out loud and you know exactly what it means. The
join
versions you have to think about.