Bool issue - changing value - c#

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().

Related

Linq check value in SQL table always is false

I tried to check if the cost or benefit value exists for the selected Id, then I will get the cost or benefit value from the table.
In the code below my if statement doesn't work and seems to always be false but the return benefit value works fine. Where is the problem?
public string GetCostBenefitAmount(int id)
{
if (db.CostBenefits.Any(c => c.ID == id && !c.Cost.Equals(0)))
{
return db.CostBenefits.Select(c => c.Cost).First().ToString();
}
return db.CostBenefits.Where(c=> c.ID == id).Select(c => c.Benefit).First().ToString();
}
This is my code in windows form for fill txtAmount textBox by GetCostBenefitAmount(int id) method:
var stockIdList = db.CostBenefitRepository.GetAllID();
int id = stockIdList[listBox.SelectedIndex];
CostBenefit costBenefit = db.GenericCostBenefitRepository.GetById(id);
txtStockName.Text = listBox.SelectedItem.ToString();
txtSoldAmount.Text = costBenefit.SoldAmount.ToString();
ComboCostBenefit.SelectedItem = db.CostBenefitRepository.GetCostBenefitOperation(id);
txtAmount.Text = db.CostBenefitRepository.GetCostBenefitAmount(id);
The Object.Equals method determines whether two object instances are equal. Try if (db.CostBenefits.Any(c => c.ID == id && c.Cost != 0)). For more info on the Object.Equals function see this post.
Edit:
As #Gert Arnold commented, the issue was in the return db.CostBenefits.Select(c => c.Cost).First().ToString(); where there was no filtering done before returning.
I think equals is only when you are using in a join. So just use
c.Cost != 0
instead.

Boolean value for linq query sets to false but is true in SQL

I'm using a linq query in my method. When I step over my linq code my isValid variable sets to false. When it needs to be true. Why is isValid getting set to false how can I fix this?
C# code
public void Method()
{
bool isValid = false;
using(Database db = new Database())
{
isValid = (from x in db.TableName
where x.Column_A = "Data_Result" &&
x.Number_Col != 11
select x).Any();
//Value of isValid = false???
}
...
}
SQL Example
SELECT * FROM TableName
WHERE Column_A = 'Data_Result' AND Number_Col <> 11
Result
The code looks good and I suspect, as TheGeneral, that the issue is that you're pointing to the wrong database.
You can verify this by getting the first few rows, top 10 maybe, and compare. Make sure you order by Id so you get the same results.
db.TableName
.OrderBy(r=>r.Id)
.Top(10);
You could add
.Where( x => x.Column_A == "Data_Result")
etc.
Update
I just noticed that you have a single equal mark in your code x.Column_A = "Data_Result". Is this your real code?

Foreach loop help c#

I'm currently trying to pull data from a database using a variable and then pass it into a foreach loop to determine if a button should be shown based on a value.
SO far I have this:
var Inter = from x in db.DT_Interviews where x.ClientID == int.Parse(ViewState["ClientID"].ToString()) && x.ClientID == CID select x;
foreach(var c in Inter)
{
if (c.InterviewDone == true)
BTI.Visible = false;
else
BTI.Visible = true;
}
However I am unable to get the loop to work! Can someone show me or explain what I am doing wrong here?
If you're trying to show BTI if any interview is associated to the viewstate client ID and having the InterviewDone flag = true, you can use:
int clientID = int.Parse(ViewState["ClientID"].ToString());
BTI.Visible = db.DT_Interviews.Any(x => x.ClientID == clientID && x.InterviewDone);
But why do you need to check that the ClientID is same as the one in the view state AND CID?
Firstly, why have you got a foreach to set 2 scenarios only i.e. set the visibility of some object to false or true. Imagine if your Inter has got 5 bool values, then the visibility of your object is dependant upon the last value in the Inter because it will continue to loop until it hits the last value. Isn't it. Try this code:
Here, I am getting a bool value in Inter as soon as it finds the first value.
var Inter = (from x in db.DT_Interviews
where x.ClientID == int.Parse(ViewState["ClientID"].ToString()) && x.ClientID == CID
select x.InterviewDone).FirstOrDefault();
if(Inter)
{
BTI.Visible = false;
}
else
{
BTI.Visible = true;
}
Your code is very strange at several places:
var Inter =
from x in db.DT_Interviews
where x.ClientID == int.Parse(ViewState["ClientID"].ToString()) && x.ClientID == CID
select x;
Are you sure that your query returns any result? what is the value of CID?
foreach(var c in Inter)
{
if (c.InterviewDone == true)
BTI.Visible = false;
else
BTI.Visible = true;
}
}
I am not sure that you are doing here? The BTI will be visible or not depeding upon the last element in your query. So, why to loop over the whole content then?

c# dealing with all possible null and non null values

I have the following method:
public IQueryable<Profile> FindAllProfiles(string CountryFrom, string CountryLoc)
{
return db.Profiles.Where(p => p.CountryFrom.CountryName.Equals(CountryFrom,
StringComparison.OrdinalIgnoreCase));
}
What is the best way to write the where clause that would filter all the possible combinations of input parameters in one statement:
BOTH CountryFrom and CountryLoc = null
Only CountryFrom null
Only CountryLoc null
BOTH CountryFrom and CountryLoc are not null.
Soon .. I would need to filter out profiles by Age, Gender, Profession .. you name it.
I am trying to find a way to write it efficiently in C#. I know how to do it in a clean manner in TSQL. I wish I knew the way. Thanks for all the responses so far.
A good old binary XNOR operation will do the trick here:
db.Profiles.Where(p => !(p.CountryFrom == null ^ p.CountryTo == null))
It's effectively equating two booleans, though to me it's more direct, less convoluted even, than writing ((p.CountryFrom == null) == (p.CountryTo == null))!
I would use this simple LINQ syntax...
BOTH CountryFrom and CountryLoc = null
var result = from db.Profiles select p
where (p.CountryFrom == null) && (p.CountryLoc == null)
select p
Only CountryFrom null
var result = from db.Profiles select p
where (p.CountryFrom == null) && (p.CountryLoc != null)
select p
Only CountryLoc null
var result = from db.Profiles select p
where (p.CountryFrom != null) && (p.CountryLoc == null)
select p
BOTH CountryFrom and CountryLoc are not null.
var result = from db.Profiles select p
where (p.CountryFrom != null) && (p.CountryLoc != null)
select p
Hope it helps ;-)
I wouldn't call this elegant:
public IQueryable<Profile> FindAllProfiles(string CountryFrom, string CountryLoc)
{
return db.Profiles.Where(p =>
{
p.ContryFrom != null &&
p.CountryFrom.CountryName != null &&
p.CountryFrom.CountryName.Equals(CountryFrom, StringComparison.OrdinalIgnoreCase)
});
}
I may be missing something, but as written, your combination of operators will either let all values through or no values through depending on whether you use || or && to combine them together.
I'm in favor of not trying to cram too much logic into a linq expression. Why not contain your comparison logic in a separate function like this?
EDIT: I provided an example implementation of the MatchesCountry function.
class Example
{
public IQueryable<Profile> FindAllProfiles(string CountryFrom, string CountryLoc)
{
return db.Profiles.Where(p => p.MatchesCountry(CountryFrom, CountryLoc));
}
}
public static class ProfileExtensions
{
public static bool MatchesCountry(this Profile profile, string CountryFrom, string CountryLoc)
{
// NOTE: Your comparison logic goes here. Below is an example implementation
// if the CountryFrom parameter was specified and matches the profile's CountryName property
if(!string.IsNullOrEmpty(CountryFrom) && string.Equals(profile.CountryName, CountryFrom, StringComparison.OrdinalIgnoreCase))
return true; // then a match is found
// if the CountryLoc parameter was specified and matches the profile's CountryCode property
if (!string.IsNullOrEmpty(CountryLoc) && string.Equals(profile.CountryCode, CountryLoc, StringComparison.OrdinalIgnoreCase))
return true; // then a match is found
// otherwise, no match was found
return false;
}
}

Comparing textbox.text value to value in SQL Server

Okay so I am trying to compare a login textbox password and username with a custom validator using linq to get information from the database it always returns false though on the validator could someone please tell me where my code below is going wrong. This will be very much appreciated... thank you in advanced...
protected void LoginValidate(object source, ServerValidateEventArgs args)
{
TiamoDataContext context = new TiamoDataContext();
var UsernameCheck = from User in context.Users
where User.Username == TextBoxLoginUsername.Text && User.Password == TextBoxLogInPassword.Text
select User.Username;
var PasswordCheck = from User in context.Users
where User.Username == TextBoxLoginUsername.Text && User.Password == TextBoxLogInPassword.Text
select User.Password;
String test1 = PasswordCheck.ToString();
String test2 = UsernameCheck.ToString();
if (test1 == TextBoxLogInPassword.Text && test2 == TextBoxLoginUsername.Text)
{
args.IsValid = true;
Session["Username"] = TextBoxLoginUsername;
Response.Redirect("UserProfile.aspx");
}
else
{
args.IsValid = false;
}
}
I dont know where I am going wrong I know its most probably some sort of silly mistake and me being inexperienced at this...
UsernameCheck and PasswordCheck are going to be collections, not single values. Therefore the ToString() method isn't returning what you think it should.
It's probably returning "IEnumerable<string>"
You need to force your LINQ queries to return a single result rather than a collection.
var user = context.Users.Where(u => u.Username==TextBoxLoginUsername.Text &&
u.Password == TextBoxLogInPassword.Text)
.FirstOrDefault();
string userNameCheck = user.Username;
string passwordCheck = user.Password;
As a side note, this is why using the var keyword is a little dangerous if you're not absolutely positive of the return type of the statement you're writing. If you would change your vars to strings, the compiler would have caught the type mismatch at compile time.

Categories