我想使用查询来使用别名到Bean转换器将对象列表映射到用逗号分隔的扁平字符串。
这是我的查询:
var query = QueryOver<WorkList>();
query.SelectList(list => list
.Select(p => p.ID).WithAlias(() => dto.ID)
.Select(p => p.Name).WithAlias(() => dto.Name)
.Select( p => p.Commodities).WithAlias(() => dto.CommodityList)
return query;
select子句中的商品是商品对象列表。现在,我想将此映射到逗号分隔的字符串。我所有的代码工作正常,但我想将其转换为逗号分隔的字符串。
我正在使用AliasToBean Transformer,在其中返回Flat Dto对象。
首先,首先,您应该在SQL Server中创建一个用户定义的函数,例如:
create function listProductCommodities(@productId INT)
returns varchar(8000)
as
begin
declare @result varchar(8000)
declare @name varchar(8000)
set @result = null
declare com_cursor cursor for
select name
from commodities
where userid = @productId
open com_cursor
fetch next from com_cursor into @name
while @@FETCH_STATUS = 0
begin
if @result is null
set @result = @name
else
set @result = @result + ',' + @name
fetch next from com_cursor into @name
end
close com_cursor
deallocate com_cursor
return @result
end
然后,您应该在子查询中使用此函数:
WorkList workList = null;
<your dto class name> dto = null;
Commodity commodity = null;
var subquery = QueryOver.Of(() => commodity)
.Where(() => commodity.ProductId == workList.ID) // instead of ProductId put your foreign key property name
.Select(Projections.SqlFunction("listProductCommodities",
NHibernateUtil.String,
Projections.Distinct(Projections.Property(() => commodity.Name))); //instead of name put your text field
var query = Session.QueryOver(() => workList)
.SelectList(list => list
.Select(p => p.ID).WithAlias(() => dto.ID)
.Select(p => p.Name).WithAlias(() => dto.Name)
.SelectSubQuery(subquery).WithAlias(() => dto.CommodityList))
.TransformUsing(Transformers.AliasToBean<your dto class name>())
.List<your dto class name>();
我对表/属性/类的名称做了一些假设,因此您应该根据需要进行调整。
但是主要思想是在SQL Server中创建函数,然后通过NHibernate的SqlFunction将此函数映射到子查询。其他数据库可能具有内置的“列表”功能,但SQL Server没有-因此,您应该解决该问题。我的listProductCommodities实现不是很好,因为它使用了游标。但是,这仅适用于少量数据。
但是还有另一个选择-您可以发出另一个sql查询以获取商品名称数组,通过string.join从该数组构建字符串,然后手动分配DTO的属性。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句