使用自联接和NHibernate Criteria API查询覆盖实体

时间:2009-05-27 18:25:19

标签: nhibernate icriteria

我有一个简单的豁免模型,我想做一个返回所有未被覆盖的豁免的查询。

public class Waiver
{
    private readonly int id;

    protected Waiver()
    {
        this.id = 0;
    }

    public virtual int Id { get { return id; } }

    public virtual string Name { get; set; }
    public virtual string Description { get; set; }
    public virtual bool IsRequired { get; set; }
    public virtual DateTime EffectiveDate { get; set; }

    public virtual Waiver OverriddenWaiver { get; set; }
}

这是地图:

  <class name="Waiver" table="Music_Waivers">
    <id name="id" access="field" column="WaiverId" unsaved-value="0">
      <generator class="native" />
    </id>

    <property name="Name" column="Name" />
    <property name="Description" column="Description" />
    <property name="IsRequired" column="IsRequired" />
    <property name="EffectiveDate" column="EffectiveDate" />

    <many-to-one name="OverriddenWaiver" class="Waiver" column="OverrideWaiverId" />
  </class>

现在我希望在我的Repository中有一个方法,其中包含签名 public IList GetLatest()。出于某种原因,我很难用CriteriaAPI实现这一点。我可以用T-SQL写这个没问题。

1 个答案:

答案 0 :(得分:0)

我最终蛮力强迫解决方案。它不漂亮,但是因为我知道桌子很小(可能最终只有5行)我想出了以下代码解决方案:

public IList<Waiver> GetLatest()
{
    using (var session = SessionManager.OpenSession())
    {               
        var criteria = session.CreateCriteria(typeof (Waiver));
        var waivers = criteria.List<Waiver>();

        var nonOverridenWaivers = new List<Waiver>();

        foreach(var waiver in waivers)
        {
            bool overrideExists = waivers.Any(w => w.Overrides != null &&
                                                   w.Overrides.Id == waiver.Id);
            if (!overrideExists)
                nonOverridenWaivers.Add(waiver);
        }

        return nonOverridenWaivers;
    }
}