我是Fluent NHibernate的完整菜鸟,我正在使用基于推荐的查询对象模式。我也是新手。我会尽量保持代码示例的简洁和有用。
用户类:
public class User {
public Guid ID { get; set; }
public string Name { get; set; }
}
可见性:
public enum VisibilityType {
Anybody,
OwnersOnly,
Nobody
}
汽车类:
public class Car {
public Guid ID { get; set; }
public VisibilityType Visibility { get; set; }
public ICollection<User> Owners { get; set; }
}
所以我需要为查询对象编写一个条件限制方法。返回所有VisibilityType.Public
的汽车,但如果汽车的Visibility
属性值为VisibilityType.OwnersOnly
,则限制返回属于该组的用户。
这是我目前使用的限制方法,但没有条件:
public class CarQueryObject
{
private User user { get; set; }
private const string OwnersProperty = "Owners";
private const string OwnersIDProperty = "Owners.ID";
public CarQueryObject RestrictToOwners()
{
// How do I add a conditional criteria here? Only restrict by owner
// if the QueryObject has VisibilityType.OwnersOnly? Note that it should
// *NOT* restrict VisibilityType.Anybody
CreateOwnersAlias();
Criteria.Add(Restrictions.Eq(OwnersIDProperty, user.Id));
return this;
}
public CarQueryObject JoinFetchOwned()
{
Criteria.SetFetchMode(OwnersProperty, FetchMode.Join);
return this;
}
public void CreateOwnersAlias()
{
Criteria.CreateAlias(OwnersProperty, OwnersProperty, JoinType.LeftOuterJoin);
JoinFetchOwned();
}
}
?_?
答案 0 :(得分:1)
获得展示汽车的想法
var carsShown = session.CreateCriteria<Car>()
.JoinAlias("Owner", "owner")
.Add(Expressions.Or(
Expression.Eq("Visibility", Visibility.Anybody),
Expression.Eq("Visibility", Visibility.OwnersOnly) && Expression.Eq("owner.Id", currentUser.Id)
))
.List<Car>();