views:

56

answers:

2

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?!?!

A: 

1-It may be because between user request , value might get changed.

2- Are you getting this value under page.IsPostBack?

saurabh
Hello Saurabh - this is just being called in page load
Ricardo Deano
A: 

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().
Peter
I love you Peter and want to have your babies : D
Ricardo Deano
I had to use return r.FirstOrDefault().GetValueOrDefault(); however as I'm using LNQ to Entities which does not get on very well with Single/SingleorDefault.
Ricardo Deano
you're welcome :-) Where I work we call these things 'sanity checks' and we ask a nearby sitting colleague to read through the code to spot things like this.
Peter