NHibernate: Convert an ICriteria to a DetachedCriteria

笑着哭i 提交于 2019-12-07 17:04:09

问题


Anyone know how to convert an ICriteria into a DetachedCriteria. I need to use an existing ICriteria as part of a subquery using:

.Add(Subqueries.PropertyIn("Name", myDetachedCriteriaSubquery))

Is there any way to convert an ICriteria to a DetachedCriteria. I will accept 'no' with a credible reference.


回答1:


Following on from mattk's answer, you can inherit DetachedCriteria to access its constructors:

public class ConvertedDetachedCriteria : DetachedCriteria
{
    public ConvertedDetachedCriteria(ICriteria criteria) 
        : base((CriteriaImpl) criteria, criteria)
    {
        var impl = (CriteriaImpl) criteria;
        impl.Session = null;
    }
}

Now you can write code like this:

var criteria = Session.CreateCriteria<Person>()
   .Add(Restrictions.Eq("Name", "John"));

var clonedDetachedCriteria = new ConvertedDetachedCriteria(criteria);

var newCriteria = Session.CreateCriteria<Person>()
    .SetProjection(Projections.SubQuery(clonedDetachedCriteria))
    .List<string>();

Disclaimer: I've only subject this to minimal testing in NH 2... no guarantees it will work or be of any use.




回答2:


var clonedDetachedCriteria = new ConvertedDetachedCriteria(CriteriaTransformer.Clone(criteria));

if Your criteria session null , create "object referans.." exception.

use CriteriaTransformer.Clone(criteria)




回答3:


DetachedCriteria has a constructor which takes an ICriteria but it is internal. It is used by CriteriaTransformer. Perhaps you could implement something similar?



来源:https://stackoverflow.com/questions/1753408/nhibernate-convert-an-icriteria-to-a-detachedcriteria

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!