开发者

Bool issue - changing value

Morning all.

I have the following method that I use to to try and bring back a bool:

public static bool GetShowCatSubProdStatus(string memberid, string username)
    {
        MyEnts showcatsubprodstatus = new MyEnts.PDC_VDSOREntities35();

        var r = from p in showcatsubprodstatus.tblKeyAccountInfoes
                where p.MemberID == memberid && p.UserName == username
                select p.ShowCatSubProd;

        return r.Any();
    }

When I call this method and debug it, the result is correct. However, when I run this method in a page load, although the method result returns the correct result, when I step through, the boolean value changes!

 bool showcatsubprodstatus = MyEnts.GetShowCatSubProdStatus(_memberid, _username);

        if (showcatsubprodstatus != true)
        {
            panCatSubProd.Visible = false;
        }

Can someone explain what is going on here and how I can solve this puzzler?!

PS: Apologies for being thick.

EDIT - Right, narrowed it down to the variable. It is always return 开发者_开发问答'true' regardless of the method result?!?!


This piece of code returns an IEnumerable<bool> :

var r = from p in showcatsubprodstatus.tblKeyAccountInfoes
        where p.MemberID == memberid && p.UserName == username
        select p.ShowCatSubProd;

By calling the .Any() you are asking it if there are any items in the IEnumerable. If there are you return true;

That is why you always get true back, because it always finds something.

The solution
Either you go for calling .SingleOrDefault() which returns the only element there is (if there is one) or returns the default value of that type.

var r = from p in showcatsubprodstatus.tblKeyAccountInfoes
        where p.MemberID == memberid && p.UserName == username
        select p.ShowCatSubProd;
return r.SingleOrDefault(); //assuming p.ShowCatSubProd is a bool and not a Nullable<bool> else you need to adjust your return type or cast it to a boolean using .GetValueOrDefault().
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜