简体   繁体   中英

How to edit NHibernate Junction using QueryOver?

Context:

I have a method to create a long Conjunction :

public static Conjunction GetLongConjunction() 
{
    Conjunction conjunction = new Conjunction();
    conjunction.Add<Person>(p => p.Id > 0);
    conjunction.Add<Person>(p => p.Age > 18);

    Disjunction disjunction = new Disjunction();
    disjunction.Add<Person>(p => p.Name == "John");
    disjunction.Add<Person>(p => p.Name == "Alice");

    conjunction.Add(disjunction);
    // ...
    return conjunction;
}

In another method, I'm using GetLongConjunction to get the conjunction:

public void AnotherMethod() 
{
    Conjunction newConjunction = GetLongConjunction();
    // ...
}

The problem is: I want to edit (or remove) one condition in newConjunction .

What I tried:

I tried to get the List<NHibernate.Criterion.ICriterion> in criteria property from AbstractCriterion class. Conjunction extends it:

Conjunction: Junction: AbstractCriterion

But criteria is a private property, and I can't get it.

Question:

So, my question is: How can I edit a NHibernate Junction? Is that possible?

Thanks!!

To keep it simple, you can use reflection:

public void AnotherMethod() 
{
    Conjunction newConjunction = GetLongConjunction();
    IList<ICriterion> criteria = newConjunction.GetCriteria();

    // Add or remove expressions
    // var disjunction = (Disjunction) criteria.Last();
}

Using this extension methods:

public static class MyExtensions
{
    public static IList<ICriterion> GetCriteria(this Junction juntion)
    {
        return juntion.GetPrivateFieldValue<IList<ICriterion>>("criteria");
    }
    public static T GetPrivateFieldValue<T>(this object obj, string propName)
    {
        if (obj == null) throw new ArgumentNullException("obj");
        Type t = obj.GetType();
        FieldInfo fi = null;
        while (fi == null && t != null)
        {
            fi = t.GetField(propName, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
            t = t.BaseType;
        }
        if (fi == null) throw new ArgumentOutOfRangeException("propName", string.Format("Field {0} was not found in Type {1}", propName, obj.GetType().FullName));
        return (T)fi.GetValue(obj);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM