微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何在linq c#中编写下面的sql查询,其中一些paramteres有时会为null

我在sql中有以下查询,

select * from dbo.WaitingLists 
where WaitingListTypeId in (1)
or StakeBuyInId in (Select StakeBuyInId from dbo.WaitingLists where StakeBuyInId in (5) and 
WaitingListTypeId = 2)

在此,有时StakeBuyInId将为null或WaitingListTypeId将为null.我想在以下代码中通过linq c#执行此查询.

public GameListItem[] GetMyWaitingList(Guid UserId,int LocalWaitingListTypeId,int GlobalWaitingListTypeId,int[] StakeBuyInIds)
            {
                ProviderDB db = new ProviderDB();

                List<GameListItem> objtempGameListItem = new List<GameListItem>();

                List<GaMetables> objGaMetablesList = new List<GaMetables>();

                var objWaitingListUser = db.WaitingLists.Where(x => x.UserId.Equals(UserId));

                if (LocalWaitingListTypeId > 0 || (GlobalWaitingListTypeId > 0 && StakeBuyInIds != null))
                {
                    objWaitingListUser = objWaitingListUser.Where(x => x.WaitingListTypeId == LocalWaitingListTypeId || (x.WaitingListTypeId == GlobalWaitingListTypeId 
                                            && StakeBuyInIds != null ? StakeBuyInIds.Contains((Int32)x.StakeBuyInId) : true)
                                         );
                }
                return objtempGameListItem.ToArray();
            }

这里StakeBuyInIds int []有时会为null,那么我将如何对上面的SQL查询执行linq操作.谢谢你的帮助.

解决方法

您可以在表达式之外检查null,如下所示:

if (LocalWaitingListTypeId > 0 || (GlobalWaitingListTypeId > 0 && StakeBuyInIds != null))
{
    if (StakeBuyInIds != null)
    {
        objWaitingListUser = objWaitingListUser.Where(
            x => x.WaitingListTypeId == LocalWaitingListTypeId || 
                 (x.WaitingListTypeId == GlobalWaitingListTypeId && 
                  StakeBuyInIds.Contains((Int32)x.StakeBuyInId));
    } else {
        objWaitingListUser = objWaitingListUser.Where(
            x => x.WaitingListTypeId == LocalWaitingListTypeId || 
                 x.WaitingListTypeId == GlobalWaitingListTypeId);
    }
}

您也可以这样做:

if (LocalWaitingListTypeId > 0 || (GlobalWaitingListTypeId > 0 && StakeBuyInIds != null))
{
    var arrayNull = StakeBuyInIds != null;
    var array = StakeBuyInIds ?? new int[0];
    objWaitingListUser = objWaitingListUser.Where(
        x => x.WaitingListTypeId == LocalWaitingListTypeId || 
             (x.WaitingListTypeId == GlobalWaitingListTypeId && 
              (arrayNotNull || array.Contains((Int32)x.StakeBuyInId)));
}

它会影响它在查询之外测试null,但确保在实际执行查询时它不能为null.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐