在Linq到NHibernate中测试条件的最佳方法是什么?

时间:2012-01-20 22:06:12

标签: c# linq nhibernate linq-to-nhibernate

Any()linq函数似乎加载了所有实体的列,即使它们不需要。

以下代码:

if(Session.Query<Project>().Any(p=>p.ID == projectID && p.ProjectOwner.Responsible == CurrentUserID))
    // Current user is the responsible for this project

生成以下SQL:

select TOP (1) project0_.ProjectID                          as ProjectID7_,
               project0_.DateCreated                        as DateCrea2_7_,
               project0_.Type                               as Type7_,
               project0_.ProjectOwner_FK                    as ProjectOy8_7_,
               project0_.Address_FK                         as Address9_7_,

**[Snip -- the statement selects all of Project's columns]**

from   [Project] project0_
       inner join [OrganizationProject] organizati1_
         on project0_.ProjectOwner_FK = organizati1_.OrganizationProjectID
where  project0_.ProjectID = 1 /* @p0 */
       and organizati1_.Responsible_FK = 1 /* @p1 */

但是,以下代码:

if(Context.Projects.Where(p=>p.ID == projectID && p.ProjectOwner.Responsible == CurrentUserID).Count() == 1)
    // Current user is the responsible for this project

生成以下sql,这是预期的:

select cast(count(*) as INT) as col_0_0_
from   [Project] project0_
       inner join [OrganizationProject] organizati1_
         on project0_.ProjectOwner_FK = organizati1_.OrganizationProjectID
where  project0_.ProjectID = 1 /* @p0 */
       and organizati1_.Responsible_FK = 1 /* @p1 */

Count()方法执行预期的操作,但它不那么简单。

Any()行为被认为是正常的还是错误的?它对我来说似乎不是最优的,但是加载实体并不比要求SQL返回计数慢?

鉴于此,什么被认为是在Linq到NHibernate中测试条件的最佳方法?

2 个答案:

答案 0 :(得分:0)

这很有趣,但你试过了吗?

if(Session.Query<Project>()
   .FirstOrDefault(p=>p.ID == projectID 
                 && p.ProjectOwner.Responsible == CurrentUserID) != null)

我认为从你目前的选择中会更快。实际上它不会检查所有项目(如计数)。它也不会获取所有数据。

答案 1 :(得分:0)

这样的事情应该创建一个只有一列的查询:

if(Session
    .Query<Project>()
    .Where(p=>p.ID == projectID && p.ProjectOwner.Responsible == CurrentUserID)
    .Select(p=>new { pID = p.ID })
    .Any())
{
   ...
}

对匿名类型的投影允许NHibernate仅获取指定的列(例如,ID)。

但是当要检索大量行时,它通常更合适。