Created
January 14, 2012 21:44
-
-
Save Buthrakaur/1613003 to your computer and use it in GitHub Desktop.
NHibernate QueryOver.List extension to support casting to anonymous types
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} |
"t" vs "dto" in your sample is a typo or not? I use it simply just as in the test I provided without any problems so far, but there may be some issues of course :)
and you can surely use it for a blog post - just provide a link to this gist and my name + website link, please..
I developed it exactly for the same purpose - simple NHibernate to json output :)
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Nice one, can I write a blog regarding this?