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?
Related
I have the following Entity Framework lambda query:
public IList<MyClass> GetMyClass(int id, bool show)
{
using (var ctx = new DbContext())
{
return ctx.MyClasses.Where(x =>
x.Id == id &&
x.Show == show // <-- nullable bool
.OrderByDescending(x => x.CreationDate).Take(100).ToList();
}
}
My front end view has passed the show boolean down indicating the users preference for what to return.
In the database, the show property is nullable.
This is a very heavy query, so I have limited it to 100 at a time, thousands of rows are null, thousands are true and thousands are false.
Question
How can I say, without making the query inefficient, psuedo code:
.Where(x => x.Show == show) (where null or false == false)
As it stands, if I pass False down, the nulls are excluded, and I need them to be classed as False.
I cannot change the database
how about
(x.Show ?? false) == show
The following code should return records with Show == True when show == true, and records with Show == False or NULL when show == false
private void Repeat(object state)
{
public IList<MyClass> GetMyClass(int id, bool show)
{
using (var ctx = new DbContext())
{
return ctx.MyClasses.Where(x =>
x.Id == id &&
(x.Show == show || !show && x.Show == null)
.OrderByDescending(x => x.CreationDate).Take(100).ToList();
}
}
}
Just another way to think about the expression. Not a good practice in LINQ to Entity.
(x.Show == true) == show
"Property or indexer cannot be assigned to -- it is read only"
i see a lot of similar question though none actually seem to help me.
i am updating some rows in my db.
first i call my data:
var projects = (from p in _ProjectRep.GetAll()
join cl in _ClientRepo.GetAll() on p.ClientID equals cl.ClientID
where p.IsOpen == true && p.Tasks.Any(t => t.TimeEntries.Any(te => te.DateEntity >= dateLimit)) == false && p.Tasks.Any(te => te.TimeEntries.Any())
select new {
TickProjectID = p.TickProjectID,
ClientName = cl.ClientName,
ProjectName = p.ProjectName,
IsOpen = p.IsOpen,
DateClosed = p.DateClosed
}).ToList();
Then i try to loop through that data, and update specific fields in those records.
foreach (var item in projects)
{// Update projects to closed.
item.IsOpen = false;
item.DateClosed = DateTime.Now;
}
and lastly save the data..
// updates changes to OUR db.
var affectedCount = _UnitOfWork.SaveChanges();
But i keep getting that error, and i do not know what to do about it.
What i can read it is something about get/set, but i have none of those,
and i cannot see why those should be nessesary ?
Hoping someone can give a clear solution, that might help me.
Edit
private readonly ProjectRepository _ProjectRep;
_ProjectRep = new ProjectRepository(unitOfWork);
var projects = (from p in _ProjectRep.GetAll()
join cl in _ClientRepo.GetAll() on p.ClientID equals cl.ClientID
where p.IsOpen == true && p.Tasks.Any(t => t.TimeEntries.Any(te => te.DateEntity >= dateLimit)) == false && p.Tasks.Any(te => te.TimeEntries.Any())
select p).ToList();
Try this. Problem in your code is, that you are working with anonymous type (created using new {...}). This type doesn't know anything like change tracking, its properties are read only, so this type can not be used to save changes to database.
it seems my sql call was anonymous, and therefore it did not know what it was.
i changed my sql call select
var projects = (from p in _ProjectRep.GetAll()
join cl in _ClientRepo.GetAll() on p.ClientID equals cl.ClientID
where p.IsOpen == true && p.Tasks.Any(t => t.TimeEntries.Any(te => te.DateEntity >= dateLimit)) == false && p.Tasks.Any(te => te.TimeEntries.Any())
select new {
Project = p,
ClientName = cl.ClientName
}).ToList();
and then i just have to call "Project.{something}" when i wanted to select data.
like this:
foreach (var item in projects)
{// Update projects to closed.
item.Project.IsOpen = false;
item.Project.DateClosed = DateTime.Now;
}
that made the whole thing work.
I have the following code:
IsServiceable = _context.Review.Any(r => r.SiteId == x.Id) ? _context.Review.All(r => r.SiteId == x.Id && r.IsValid == true) : true
But as you can see it is not effective because I try to access the database twice in the same row.
I need to write single query(LINQ TO ENTITY) to check if the table named Reviews
has at least one row
where siteId=5 if it doesn't it has to return true,
If table Reviews has at least one row I need to check a boolean column named isValid if, there is at least one row where siteId=5 and isValid column is false I need to return false.
I believe your solution lies in the fact that only in one case do you need to return false - everything else returns true. Therefore, if you find one row where sideId=5 and isValid = false, then return false. Otherwise, return true. Based on your code, I suggest something like the following:
IsServiceable = _context.InspectionReview.Any(r => r.SiteId == x.Id && r.isValid == false) ? false : true;
You most likely have navigation properties so you could try
IsServiceable = _context.Site.Any(s => s.Id == x.Id && s.Reviews.Any(r => r.IsValid));
I have multiple drop-down lists with default value of 0 which indicates that user not selected any option and other numbers with mean user selected an value and it should include in LINQ query. My problem is I can not check if the user selected any options in drop-down lists or not?
This is my try for first drop-down list:
var ddl1 = Convert.ToInt32(ddlDastgAhasli.SelectedValue);
var project = (from p in context.Projects
where Convert.ToInt32(p.DastgahEjraeiAsli) == ((ddl1 == 0) ? null : ddl1) select p);
This is the error:
type of conditional expression cannot be determined because there is no implicit conversation '' and 'int'
You have two problems here:
You cant compare a value type(in your case int) to null.
You need to select something.
This is the structure for the query:
var project = (from p in context.Projects where p.prop == 1 select p);
And this to parse the int:
Bad
string strInt = "7";
if(Convert.ToInt32(strInt) == null) // compilation error
Good
string strInt = "7";
int intVal;
if(int.TryParse(strInt, out intVal))
{
// intVal is an integer
}
else
{
// intVal isnt an integer
}
If you just want to skip the where condition when ddl1 isn't set, you can just conditionally add the where clause when actually needed, something like (with the somewhat silly example of all ddls comparing to the same field)
var project = (from p in context.Projects select p);
if(ddl1 != 0)
{
project = project.Where(Convert.ToInt32(p.DastgahEjraeiAsli) == ddl1);
}
if(ddl2 != 0)
{
project = project.Where(Convert.ToInt32(p.DastgahEjraeiAsli) == ddl2);
}
...
This will effectively require all where clauses where ddlx != 0 to be true, and the ones where the ddl is 0 are not in any way affecting the query.
Here is a very useful extension method which i use in my projects to solve various checks..Its not about only ASP.NET..You can use it in winforms etc. also
public IEnumerable<Control> GetAll(Control control)
{
var controls = control.Controls.Cast<Control>();
return controls.SelectMany(ctrl => GetAll(ctrl))
.Concat(controls)
.Where(c => c.Visible == true);
//If you don't need to check that the control's visibility then simply ignore the where clause..
}
with this method no matter your control (in your situation dropdownlists) is a member/child of another control under that control which the control you pass as parameter to the method..Method checks recursively started from given parameter and checks all child controls related to given control as Method parameter..
And Usage in code :
//Its Assumed you need to check DropDownList' SelectedIndex property
List<Control> dropDownsOfPageWhichTheirSelectedIndexIsZero
= new List<Control>( GetAll ( YourAspNetPage )
.Where( x => x is DropDownList
&& ( ( DropDownList ) x ) . SelectedIndex == 0 ) ) ;
// Lets check if our page has dropdowns which their SelectedIndex equals to Zero
if ( dropDownsOfPageWhichTheirSelectedIndexIsZero . Count > 0 )
{
// do your work what you need in your project
//suppose you need their names and do something with this name (i.e.warn a message to user)
foreach ( DropDownList ddl in dropDownsOfPageWhichTheirSelectedIndexIsZero )
{
alert ("Please Check "+ ddl.Name +".Should Chost other than \"Select\" option");
}
}
Hope this Helps..
problem solved by putting "Convert.ToInt32(p.DastgahEjraeiAsli)" instead of null, so if the ddl1 == 0 (user hasn't selected any item) where skips.
var project = (from p in context.Projects
where Convert.ToInt32(p.DastgahEjraeiAsli) == ((ddl1 == 0) ? Convert.ToInt32(p.DastgahEjraeiAsli) : ddl1) select p);
this is very useful when for example u have a search form with multiple texboxs and dropdownlists and user may choose each of them and you do not know which one will be selected and which one not.
simplified example :
in the search button click event:
int ddl1 = Convert.ToInt32(dropdownlist1.selectedvalue);
int ddl2 = Convert.ToInt32(dropdownlist2.selectedvalue);
string txt1 = textbox1.text;
var project = (from p in context.mytable
where p.field1 == ((ddl1 == 0) ? p.field1 : ddl1)
&& p.field2 == ((ddl2 == 0) ? p.field2 : ddl2)
&& p.field3 == ((txt1 == "") ? p.field3 : txt1)
select p).ToList();
gridview1.datasource = project;
fridview1.databind();
not: each dropdownlist has a default value with text="select an item" and value="0", so if user didn't select any option default value remains 0.
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().