Question

Is there any way to compare generic types in linq query to translate to SQL with NHibernate?

Something like this:

public abstract class DataProviderBase<TDAO, TId>
{
    protected ISession Session;

    public virtual TDAO GetById(TId id)
    {
        var allItems = GetAllQuery();  // gives me query, usually Session.Query<TDAO>();
        var res = allItems.SingleOrDefault(item => item.Id == id);
            // !!! Operator '==' cannot be applied to operands of type 'TId' and 'TId'
        return res;
    }

    protected virtual IQueryable<TDAO> GetAllQuery()
    {
        var query = Session.Query<TDAO>();
        return query;
    }
}

I know I can use Session.Get<TDAO>(id);, but that is not what I am going for. GetAllQuery() is a virtual method and i want to be able to override it.

  • NHibernate version: 3.3.3.4000
  • NHibernate.Linq version: 1.0

Thanks

Was it helpful?

Solution

You can create your predicate dinamically. For example:

var parameter = Expression.Parameter(typeof (TDAO));
var predicate = Expression.Lambda<Func<TDAO, bool>>(
    Expression.Equal(Expression.Property(parameter, "Id"),
                     Expression.Constant(id)),
    parameter);
var res = allItems.SingleOrDefault(predicate);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top