实体框架。方法链接 [英] Entity Framework .Where method chaining

查看:97
本文介绍了实体框架。方法链接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这两种方式查询上下文有什么区别?

Is there any difference between these two ways of querying the context?

Firm firm = base.context.Firms
            .Where(f => f.SomeId == someId)
            .Where(f => f.AnotherId == anotherId)
            .FirstOrDefault();

Firm firm = base.context.Firms
            .Where(f => f.SomeId == someId && f.AnotherId == anotherId)
            .FirstOrDefault();

似乎链接完成了AND条件。我不相信你可以链接OR语句。是否有理由选择一个或另一个更好/更高效的场景?

It seems that chaining is perfectly fine to accomplish the AND condition. I don't believe you can chain OR statements. Is there a reason to prefer one over another, or scenarios when one is better/more efficient?

推荐答案

他们应该产生相同的最终结果(如果我没有错误),但我发现第二个更可读,更好地显示了原来的意图。

They should both produce the same end result (if I'm not mistaken) but I find the the second is more readable and better shows the original intent.

更新

我刚刚使用LINQPad验证了上述语句。实际上,这两个查询将产生相同的SQL。

I just verified the above statement using LINQPad. Both queries will, in fact, product the same SQL.

例如:

context.SomeTable.Where(c => c.ParentId == null)
                 .Where(c => c.Name.Contains("F"))
                 .Select(c => c.Name);

产生:

SELECT [t0].[Name] 
FROM [SomeTable] AS [t0]
WHERE ([t0].[Name] LIKE @p0) AND ([t0].[ParentId] IS NULL)

与以下产生的SQL相同:

Which is the same SQL that is produced by:

context.SomeTable.Where(c => c.ParentId == null && c.Name.Contains("F"))
                 .Select(c => c.Name);


您还可以更多地压缩一些东西(由于与上述相同的原因,我觉得最好):

You could also compact things a little more (which I find preferable for the same reasons as above):

var firm = base.context.Firms.FirstOrDefault(f => f.SomeId == someId 
                                                  && f.AnotherId == anotherId);

这篇关于实体框架。方法链接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆