在nHibernate中使用CreateCriteria向连接添加限制

时间:2012-02-03 16:49:22

标签: hibernate nhibernate fluent-nhibernate

初学者问题我确定:

我正在尝试在两个表之间进行连接并同时限制结果:

var bookings = session.CreateCriteria<Booking>("p")
                       .CreateCriteria("p.BookingLocations", JoinType.InnerJoin)
                       .Add(Restrictions.Eq("p.BookingLocations.locationID", locationId))
                       .SetMaxResults(30)
                       .List<Booking>();

我收到错误: 无法解析属性:BookingLocations.locationID:预订

我可以看到Booking.BookingLocation包含许多记录,因为Booking和BookingLocation之间存在一对多关系,但我不确定这是否是导致问题的原因。

我想如果是的话我需要做类似的事情:

.Add(Restrictions.Eq("p.BookingLocations.first().locationID", locationId))

......但毫无疑问,这不起作用;)

public class Booking
{
    public virtual int Id { get; set; }
    public virtual Int32 bookingID { get; set; }
    public virtual Int32 bookingAdminID { get; set; 
}

public class BookingLocation
{
    public virtual int Id { get; set; }
    public virtual Int32 bookingID { get; set; }
    public virtual Int32 locationID { get; set; } 
}

映射

 public BookingMap()
 {
    Table("Bookings");

    Id(x => x.Id).Column("ID");
    Map(x => x.bookingID).Column("BookingID");
    Map(x => x.bookingAdminID).Column("BookingAdminID");
 }

public class BookingLocation
{
    public virtual int Id { get; set; }
    public virtual Int32 bookingID { get; set; }
    public virtual Int32 locationID { get; set; } 
 }

1 个答案:

答案 0 :(得分:7)

子标准定义了一个新的范围,它以BookingLocation为根。您只需使用locationID

session.CreateCriteria<Booking>("p")
       .CreateCriteria("p.BookingLocations", JoinType.InnerJoin)
       .Add(Restrictions.Eq("locationID", locationId))