Disjunction on QueryOver<T> always refers to root entity

China☆狼群 提交于 2019-12-05 17:19:25

try in this way, I've inserted some random conditions and I used Aliases

 var qOver = _session.QueryOver<User>(() => usr)         
     .JoinAliases(() => usr.Programs, prg, JoinType.LeftOuterJoin)
     .Where(Restrictions.Or(
                Restrictions.On(() => usr.ID).IsIn(MyValue)
                ,Restrictions.Or(
                   Restrictions.On(() => prg.ID).IsIn(MyValue)
                  , Restrictions.On(() => prg.ID).IsNull)
                 )
               )
     .List<User>();

In this way your SQL code will be the following

SELECT ....
FROM User
INNER JOIN Program On (...conditions...)
WHERE User.ID = 'MyValue'
OR (Program.ID IN ('Value1','Value2') OR Program.ID IS NULL)

I hope it's helpful

ctrlplusb

You can get around the magic strings as @Faber suggests in his answer.

I had a similar problem also requiring dates. Here is my code:

var disjunction= new Disjunction();

disjunction.Add(Restrictions.On<LocalAsset>(e => e.AvailableFrom).IsBetween(startDate).And(endDate));
disjunction.Add(Restrictions.On<LocalAsset>(e => e.AvailableTo).IsBetween(startDate).And(endDate));

query.Where(disjunction);

I came up with this solution (unfortunatly I didn't manage to get rid of magic strings)

protected Disjunction GetChangedDisjunction<T>(string alias, Disjunction junction = null) where T : IHaveDate
    {
        if(junction == null)
            junction = new Disjunction();

        var toDatum = DateTime.Now;
        junction.Add(Restrictions.And(
                        Expression.Gt(string.Format("{0}.DeletedDate", alias), fromDate), 
                        Expression.Lt(string.Format("{0}.DeletedDate", alias), toDate)));
        junction.Add(Restrictions.Gt(string.Format("{0}.CreatedDate", alias), fromDate));
        junction.Add(Restrictions.Gt(string.Format("{0}.UpdatedDate", alias), fromDate));

        return junction;
    }

and then I use it like this:

User userAlias= null;
var queryOverUser = QueryOver.Of( () => userAlias);

Program programAlias = null;
queryOverUser 
    .JoinQueryOver(a => a.Programs, () => programAlias, JoinType.LeftOuterJoin)

Disjunction disjunction = new Disjunction();
GetChangedDisjunction<User>("userAlias", disjunction);
GetChangedDisjunction<Program>("programAlias", disjunction);

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