Adding more than one condition in Projection.Conditionals for queryover

浪子不回头ぞ 提交于 2019-12-10 18:06:48

问题


I am trying to write a case with more than one when clause; something like this:

...
case
    when 'starks' then 1
    when 'wildlings' then 2
    when 'lannisters' then 3
    Else 0
End
...

I've done a single conditional before with something like

.OrderBy(Projections.Conditional(
    Restrictions.Where<House>(r => r.Name.IsLike("starks")),
    Projections.Constant(0),
    Projections.Constant(1))).Asc();

But I can't figure out how to add an extra condition / when clause in there :/ I've tried adding an extra outer conditional, extra restriction etc, but always end up with syntax error..

Thanks for the help.


回答1:


The Projections.Conditional returns IProjection, and its signature is:

/// <summary>
/// Conditionally return the true or false part, dependention on the criterion
/// </summary>
/// <param name="criterion">The criterion.</param><param name="whenTrue">The when true.
///    </param><param name="whenFalse">The when false.</param>
/// <returns/>
public static IProjection Conditional(ICriterion criterion
                                    , IProjection whenTrue
                                    , IProjection whenFalse);

And that means, that the third parameter can again be this Conditional projection:

.OrderBy
(
    Projections.Conditional(
        Restrictions.Where<House>(r => r.Name.IsLike("starks")),
        Projections.Constant(1),
        Projections.Conditional(
            Restrictions.Where<House>(r => r.Name.IsLike("wildlings")),
            Projections.Constant(2),
            Projections.Conditional(
                Restrictions.Where<House>(r => r.Name.IsLike("lannisters")),
                Projections.Constant(3),
                Projections.Constant(0)
                )
            )
        )
)
.Asc()

The generated SQL will look like:

ORDER BY 
(case when this_.Name LIKE 'starks'     then 1 else 
(case when this_.Name LIKE 'wildlings'  then 2 else 
(case when this_.Name LIKE 'lannisters' then 3 else 0 end) end) end) asc


来源:https://stackoverflow.com/questions/24043747/adding-more-than-one-condition-in-projection-conditionals-for-queryover

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!