Asp.net - Complex Linq Query - Add A .Where() Or .Any() Predicate To Reduce Query Complexity (in VB)?
Sep 14, 2010
I have to join two main tables, and I need to filter the results by elements in an ASP.NET web form. These filters are created on the fly so I have to use a lot of where extensions to filter the query. I want to execute the query with as optimized SQL as possible.
I am first doing a simple join between TW_Sites and TW_Investigators. Then there are two sub-tables that are involved. TW_InvestigatorToArea and TW_InvestigatorToDisease. While most of the where clauses are working fine, I have found a performance issue that won't be an issue right now, but will be an issue as the table gets bigger.
The arrays DiseaseCategories and DiseaseAreas would be the results of a CheckBoxList result.
Protected Sub LoadResults()
'Get Dictionary of Filters
Dim FilterDictionary As OrderedDictionary = Session.Item("InvestigatorFilterDictionary")
' Initialize LinqToSql
I know that LINQ queries are deferred and only executed when the query is enumerated, but I'm having trouble figuring out exactly when that happens.Certainly in a For Each loop, the query would be enumerated.What's the rule of thumb to follow? I don't want to accidentally enumerate over my query twice if it's a huge result.
For example, does System.Linq.Enumerable.First enumerate over the whole query? I ask for performance reasons. I want to pass a LINQ result set to an ASP.NET MVC view, and I also want to pass the First element separately. Enumerating over the results twice would be painful.It would be great to turn on some kind of flag that alerts me each time a LINQ query is enumerated. That way I could catch scenarios when I accidentally enumerate twice.
I need to display data from a complex sql query controlled by 2 combos. The sql main query part is working fine but I cannot get to link the combos to the query. On form load I load combo1 by means of a sub. Then with SelectedIndexChanged I load the combo2. Both combos load fine by do not intereact with eachothers meaning combo1 doen't filter out combo2's information.
I'm trying to update an access .mdb file. The file contains one table with 115 fields. I have estabished a connection to the database. I'm able to select the datarow I want to update. I can see it when I debug the code. I change two fields in the datarow by using thier index.
I was wandering is it possible to use a query within another query below is the code I am trying to use.
Public Function GetInventByComp(ByVal CompID As String) Using DC As New DataClassDataContext 'need to get company id's based off names? thats bad should be name from Id need to rethink this Dim invent = (From C In DC.Inventors_Companies _ Where C.CompID = CompID _ Select C.InventorID).ToString
[Code]...
I was trying to us multiple values in a string like "1, 3, 5" but I can't seem to get that working either so I am trying to use just a single value now. Can anyone help me? "Yes I am new to this"
What I am about to do build is a UI that will allow a power user to build complex queries.
This is non-trivial, but very common. So before I re-invent the wheel, I would like to see if anybody can point me to some already-written free code or release some of their own.
Required:
To be able to specify some 'where-clause' type logic like this: Age>21 and (Citizen=True or HasGreeCard=True) but without having to type the query code, instead, use a UI with constrained options and on-the-fly syntax checking (e.g., no unclosed parenthesis or ending a term with an Operator).
I've seen this type of thing in many line-of-business apps, where you can say 'add condition' and another line appears on the UI like this:
Dropdown of fields Dropdown of ops (=, >, etc) Blank box for entry
And you can add more lines, and the lines are all and'ed, but you can also decide to OR a few, or insert parenthesis (explicity or via indenting), NOT a line, insert, delete, and move lines around, etc.
Not required but nice:
WPF - I could convert from winforms. Extensibility using OO constructs. Validate the sanity of the query. Emit a System.Linq.Expressions expression tree - or similar data structure. If it attempts to execute the query I don't need that; but I don't mind removing it.
When Creating a query using the sear Criteria Builder . I keep getting the error : "The schema returned by the new query differs from the base query" what does that mean and how do i avoid this problem in future
Forgive my ignorance on this.I have this LINQ Query:Dim ngBikersDataContext As New CarBikeWalkDataContext
bikersList = (From c In ngBikersDataContext.Reg_Bikers _ Order By c.L_Name _ Select New Bikers() With { _ .BikerID = c.BikerID, _ .F_Name = c.F_Name, _
[Code]...
with the error "Overload resolution failed because no accesible 'Select' accepts this number of arguments." Over the "NEW" I get an error " ')'expected."
I've been reading a fair bit about the performance of using LINQ rather than using a for each loop and from what I understand using a LINQ query would be a little bit slower but generally worth it for convenience and expressiveness. However I am a bit confused about how much slower it is if you were to use the results of the query in a for loop.
Let's say that I have a set called 'Locations' and a set of objects called 'Items'. Each 'item' can only belong to one 'location'. I want to link items that are under the same location to each other. If I were to do this using a normal 'For Each' loop it would be something like this:
For Each it as Item in Items If it.Location.equals(Me.Location) Me.LinkedItems.Add(it) End If Next
However if i was to use LINQ it would instead be this:
For Each it as Item in Items.Where(Function(i) i.Location.equals(Me.Location)) Me.LinkedItems.Add(it) Next
is the second (LINQ) option going to loop once through the entire 'Items' set to complete the query, then loop through the results to add them to the list, resulting in essentially two loops, or will it do the one loop like the first (For Each) option?
Is it possible to do the following? [code] Basically I have one Load_Gridview function that is called on all postbacks, and rather than creating a bunch of different cases.I want the filters to stack.My actual code has more filters set up (4 or 5 of the).It all compiles ok but when I run and try to execute with active checked, or a department selected I get the following error. [code]
We are doing a query against an in-memory collection of LINQ data objects. The wrinkle is that we are ordering by a column in a related table whose records have not necessarily been loaded yet (deferred loading:)
Dim oPkgProducts = _ From b In oBillPkg.BillProducts _ Where b.Successful.GetValueOrDefault(Common.X_INDETERMINATE) = _
How do I add ROW_NUMBER to a LINQ query or Entity? How can I convert this solution to VB.NET?
[Code]...
I'm having trouble porting that last line. I have been unable to locate a VB.NET example. I'm actually not looking for any paging functionality like the example provides, just good old-fashioned Row_Number(Order By X) row index.
I have been trying the following but it returns unexpected results:
Dim xd As XDocument = _ <?xml version="1.0" encoding="utf-8"?> <root>
[code].....
The above result returns both 'element' nodes however it should only return the first where element/subelement@id=1/subsubelement@id=3 However if results.Ancestors. is used it returns the correct 'subelement' and if that line is not included it returns a single 'subsubelement' whih is also correct I don't understand why when mvoing to the 'element' it returns both (I realise both have a subelement with id=1 but I thought each further query would filter out the presvious results)?
I have a List of Price Objects (Price contains Date, High, Low) and am trying to extract monthly averages via LINQ. I have this working in C# but we have a few legacy applications that need it in VB.Net and I can't quite seem to figure out the conversion. I've even tried breaking it into two queries to no avail.
Ok im trying to do a if statement in Linq and was wondering if it was possible to do something like:
Dim loadFriends = From p In db.UserRelationships Where p.aspnet_User.UserName = User.Identity.Name _ Or p.aspnet_User1.UserName = User.Identity.Name And p.Type = 1 _ Select New With {if p.aspnet_user1.user = "a certan username" then .username = _ p.aspnet_user.username else .username = p.aspnet_user1.Username}
Dim query = From o In myContainer.MyObjects Select o.MyStringProperty Distinct Dim myProperties As List(Of String) = query.ToList????? 'no way!!!' "query" type is IEnumerable(Of String)
I tried to use the query directly as a DataSource of a (infragistic) combobox, but it throws me NullReferenceException, so I decided to convert it to a listof strings, to be a more "classical" datasource.
Dim values As List(Of String) = query.AsQueryable().ToList() does not work either: Value of type 'System.Collections.Generic.List(Of System.Linq.IQueryable(Of String))' cannot be converted to 'System.Collections.Generic.List(Of String)'.
In this query against a datatable i'm trying to do some conditional filtering.The check against Timeband(index N) should only be done when the Index exists. (the base code only had three item fields, i've converted them to a simple list)
Dim res As DataTable = ( From dr As DataRow In dtTimedRow.AsEnumerable() Select dr
[code]....
The above code triggers an Exception if the count = 1. It executes the code next to imeBands.Count > 1 which it should not. What would be the correct solution for this code.In the mean time i've added a simple filter function.
I have this query that I tried to join 2 tables together, one which holds the product name, and product numbers, and take a product number, and go to the other where to find a Art_no which is like the product number.[code]
I have the following query in VB, but I do not know how to translate it to C# synatax
Dim q = From c In db.Customers Group Join o In db.Orders On c.CustomerID Equals o.CustomerID Into orders = Group Select New With {c.ContactName, .OrderCount = orders.Count()}
I want to write a query that the "where" in the query is a string something like"
Dim query as string= "Name =xxxx and Date > 10 " Dim t = from book in doc.Descendants("books") Select _ [Name] = book..value, [Date] = book..value.... Where (query)