Skip to content

Instantly share code, notes, and snippets.

@zeqk
Forked from Buthrakaur/gist:1613003
Created January 12, 2018 00:35
Show Gist options
  • Save zeqk/e51ca8ad4366af6f6e5eb165a2a71442 to your computer and use it in GitHub Desktop.
Save zeqk/e51ca8ad4366af6f6e5eb165a2a71442 to your computer and use it in GitHub Desktop.
NHibernate QueryOver.List extension to support casting to anonymous types
public static IList<TRes> ListAs<TRes>(this IQueryOver qry, TRes resultByExample)
{
var ctor = typeof (TRes).GetConstructors().First();
return qry.UnderlyingCriteria
.SetResultTransformer(Transformers.AliasToBeanConstructor(ctor))
.List<TRes>();
}
[Fact]
public void ListAs_Should_CastQueryOverResultToTypeSameAsSupliedExampleInstance()
{
var t = new { id = 0L, name = string.Empty };
var data = Session.QueryOver<X>()
.Where(x => x.Id == 123)
.SelectList(sl => sl
.Select(x => x.Id).WithAlias(() => t.id)
.Select(x => x.Name).WithAlias(() => t.name)
)
.ListAs(t);
Assert.Single(data);
Assert.Equal(123L, data[0].id);
Assert.Equal("name", data[0].name);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment