问题
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