Skip to content

Instantly share code, notes, and snippets.

@vas6ili
Created December 4, 2012 10:17
Show Gist options
  • Save vas6ili/4202435 to your computer and use it in GitHub Desktop.
Save vas6ili/4202435 to your computer and use it in GitHub Desktop.
Helper extension methods for creating a list of ASP.NET MVC SelectListItem with NHibernate LINQ
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Web.Mvc;
using NHibernate;
using NHibernate.Linq;
public static class SelectListExtensions
{
private static readonly PropertyInfo TextProperty = typeof(SelectListItem).GetProperty("Text");
private static readonly PropertyInfo ValueProperty = typeof(SelectListItem).GetProperty("Value");
public static IList<SelectListItem> SelectListItems<TEntity>(
this IQueryable<TEntity> query,
Expression<Func<TEntity, string>> text,
Expression<Func<TEntity, string>> value)
{
var param = Expression.Parameter(typeof(TEntity), "x");
var projection = Expression.Lambda<Func<TEntity, SelectListItem>>(
Expression.MemberInit(
Expression.New(typeof(SelectListItem)),
Expression.Bind(TextProperty, Expression.Invoke(text, param)),
Expression.Bind(ValueProperty, Expression.Invoke(value, param))
),
param
);
return query.Select(projection).ToList();
}
public static IList<SelectListItem> SelectListItems<TEntity>(
this ISession session,
Expression<Func<TEntity, string>> text,
Expression<Func<TEntity, string>> value)
{
return session.Query<TEntity>().SelectListItems(text, value);
}
}
// no filtering
var countries = session.SelectListItems<Country>(x => x.Name, x.Id.ToString());
// with filtering
var countries = session.Query<Country>().Where(x => x.Continent == "Europe").SelectListItems(x => x.Name, x => x.Id.ToString());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment