开发者

How do I optimize ICriteria to select in NHIbernate?

First of all, I'm sure there must be a simple solution to this but I just can't find it. (Yes, I have googled it)

If I run this Criteria..

IList<Team> teams = session.CreateCriteria<Team>("t")
.CreateCriteria("t.TeamMembers", "m")
.Add(Expression.Eq("m.Enabled", true))
.List<Team>();

..the generated SQL is similar to:

SELECT t.*, m.* FROM Teams t INNER JOIN TeamMembers m ON t.ID = m.TeamID

Since I only need the columns from table Teams. How do I instruct NHibernate stop fetching the unused columns from TeamMembers?

(My real implementation is quite complex which returns lots of data so this is a simplified example for brevity)

EDIT: " Added: .Add(Expression.Eq("m.Enabled", true))" to the Criteria

Here's a test I made with the same setup:

Classes:

public class Team
    {
        public virtual int ID { get; private set; }
        public virtual Iesi.Collections.Generic.ISet<Member> Members { get; set; }
    }

    public class Member
    {
        public virtual int ID { get; private set; }
        public virtual bool Enabled { get; set; }
        public virtual Team Team { get; set; }
    }

Mappings:

<class xmlns="urn:nhibernate-mapping-2.2" name="TestApp.Team, ClassLib" table="`Team`">
    <id access="backfield" name="ID" type="System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
      <column name="ID" />
      <generator class="identity" />
    </id>
    <set lazy="true" name="Members">
      <key>
        <column name="TeamID" />
      </key>
      <one-to-many class="TestApp.Member, ClassLib" />
    </set>
  </class>
  <class xmlns="urn:nhibernate-mapping-2.2" name="TestApp.Member, ClassLib" table="`Member`">
    <id access="backfield" name="ID" type="System.Int32, mscorl开发者_运维问答ib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
      <column name="ID" />
      <generator class="identity" />
    </id>
    <property name="Enabled" type="System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
      <column name="Enabled" />
    </property>
    <many-to-one class="TestApp.Team, ClassLib" name="Team">
      <column name="TeamID" />
    </many-to-one>
  </class>

Generated SQL:

 SELECT this_.ID as ID11_1_, m1_.ID as ID10_0_, m1_.Enabled as Enabled10_0_, m1_.TeamID as TeamID10_0_ FROM "Team" this_ inner join "Member" m1_ on this_.ID=m1_.TeamID WHERE m1_.Enabled = @p0;@p0 = True [Type: Boolean (0)]

Note for clarification: I incidentally named the TeamMembers to Members in my test example.


UPDATED FOR UPDATE QUESTION

It's probably best to make the Members collection lazy in the configuration

<set name="Members" lazy="true">

and then only set otherwise when required like

.SetFetchMode("TeamMembers", FetchMode.Eager) 
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜