我正在尝试使用Fluent NHibernate编写动态查询,并努力研究如何应用动态where标准。
这适用于ASP.NET MVC5项目,我希望在视图中显示DTO表,用户可以在任何行上应用过滤器。出于性能原因,必须将过滤器传递给数据库。
说我有以下类定义:
// Entity in database
public class EntityA
{
public int Id {get; set;}
public string Name {get; set;}
public IEnumerable<EntityB> Children {get; set;}
}
// Entity in database
public class EntityB
{
public int Id {get; set;}
public string Name {get; set;}
public EntityA Parent {get; set;}
}
// DTO that is displayed in view / filter criteria is based on
public class Dto
{
public int Id {get; set;}
public string AName {get; set;}
public string BName {get; set;}
}
我在IEnumerable<FilterProperty>
中收到用户的过滤条件,如下所示:
public class FilterProperty
{
public string Name {get; set;}
public dynamic Value {get; set;}
}
我的NHibernate查询如下:
EntityA aliasA = null;
EntityB aliasB = null;
Dto aliasDto = null;
var query = QueryOver.Of(() => aliasB)
.JoinAlias(() => aliasA.Parent, () => aliasA)
.SelectList(l => l
.Select(() => aliasB.Id).WithAlias(() => aliasDto.Id)
.Select(() => aliasA.Name).WithAlias(() => aliasDto.AName)
.Select(() => aliasB.Name).WithAlias(() => aliasDto.BName)
)
.TransformUsing(Transformers.AliasToBean<Dto>());
我难倒的地方是如何将针对DTO的过滤器的平面列表转换为针对我可以传递给.Where()
NHibernate方法的实体对象的表达式树?
转化后是否可以应用限制标准?
答案 0 :(得分:0)
您可能希望为此创建单独的方法/辅助/转换器。
Dictionary<string, string> mappings = new Dictionary<string, string>(){
{"Id", "aliasB.Id"},
{"AName", "aliasA.Name"},
{"BName", "aliasB.Name"}
};
List<FilterProperty> filters = new List<FilterProperty>();
Junction filterCreteria = Restrictions.Conjunction();
foreach (var filter in filters)
{
var mappedPropertyName = mappings[filter.Name];
filterCreteria.Add(Restrictions.Eq(mappedPropertyName, filter.Value));
}
.Where(filterCreteria)