-->

Does anyone know how to translate LINQ Expression

2020-08-01 05:20发布

问题:

Does anyone know of an existing solution to translate a LINQ Expression to HQL statement?

Thanks in advance to all the good samaritans out there.

P.S.

We already use Linq to NHibernate. However, it only works for select statements, whereas HQL is good for other statement kinds, like delete. So, Linq to NHibernate is not the answer.

回答1:

Linq to nhibernate has just been released . Does that help?



回答2:

I had the exact same need: I needed to delete using a LINQ expression, but NHibernate only supports delete using HQL or SQL. I don't like this approach, since the rest of the code is completely strongly typed with LINQ expression, and I then had to relate to table and property names and manipulating strings.

I am working with NHibernate 3.0 and I came 95% of the way, but I had to use reflection to call some private/internal methods on the way. The below gives me an HqlQuery object for the LINQ expression:

NhQueryable<Product> queryable = (from p in session.Query<Product>()
                             where p.ProductId == 1
                             select p) as NhQueryable<Product>;
            if (queryable != null)
            {
                Expression expression = queryable.Expression;
                NhQueryProvider provider = queryable.Provider as NhQueryProvider;
                MethodInfo prepareQueryMethod = typeof(NhQueryProvider).GetMethod("PrepareQuery", BindingFlags.Instance | BindingFlags.NonPublic);
                object[] arguments = new object[] {expression, null, null};
                NhLinqExpression nhLinqExpression = prepareQueryMethod.Invoke(provider, arguments) as NhLinqExpression;
                ExpressionToHqlTranslationResults translationResults = nhLinqExpression.ExpressionToHqlTranslationResults;
                HqlQuery hql = translationResults.Statement as HqlQuery;
            }

I am stuck on that I am not able to convert the HqlQuery object to a HQL string. Anyone have any input on this? Or did you solve your problem in a different way?

Anyway I think it could be a great addition to have an overload of ISession.Delete, that took an IQueryable or IQuery as parameter. I am a newbie to NHibernate, but it seems to me it should be a fairly simple task for someone knowing NHibernate to find some already existing methods and wire them up to do the job.



回答3:

Use LINQ for querying, HQL for delete and update. Even Criteria can still be useful sometimes instead of LINQ.

It's not an either/or situation, you can and should pick the best tool for each job.