Extending LINQ to Nhibernate provider, in combination with Dynamic LINQ problem

泪湿孤枕 提交于 2019-11-30 14:41:20

I had the same problem and fixed it.
At first I want to thank murki for providing the information which got me on my way!

The answer lies partly in Fabio's post. To solve this issue you have to use the RegisterGenerator instead of the Merge method in the CustomLinqToHqlGeneratorsRegistry constructor. My implementation of the CustomLinqToHqlGeneratorsRegistry class is as follows:

public class CustomLinqToHqlGeneratorsRegistry : DefaultLinqToHqlGeneratorsRegistry
{
    public CustomLinqToHqlGeneratorsRegistry()
        : base()
    {
        MethodInfo toStringMethod = ReflectionHelper.GetMethodDefinition<int>(x => x.ToString());
        RegisterGenerator(toStringMethod, new ToStringGenerator());
    }
}

There are two, well defined, separate stages here:

  1. Converting the dynamic (string) query into a static expression (done by the Dynamic Linq library)
  2. Parsing that into an HqlTree, then executing (done by NHibernate)

Since you have determined that a static expression works well, the problem lies in 1.

What happens if you do the following?

var results = Enumerable.Empty<Project>().AsQueryable();
string pId = "1";
results = results.Where("Id.ToString().Contains(@0)", pId);

If it fails, you'll have confirmed it's a problem with Dynamic Linq alone (i.e. it doesn't support the expression you're feeding it), so you'll have to dig into it and patch it.

Semi-related: the ToStringGenerator looks useful; could you submit a patch for NHibernate? http://jira.nhforge.org

Supposing the property Id of the class Project it's an Int32 try registering the corresponding Int32.ToString() method in your ToStringGenerator class.

...
public ToStringGenerator()
{
    SupportedMethods = new[]
        {
            ReflectionHelper.GetMethodDefinition<object>(x => x.ToString()),
            ReflectionHelper.GetMethodDefinition<int>(x => x.ToString()),
        };
}
...
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!