Linq Query in VB - vb.net

Good Day,
I am querying my database using Linq and I have run into a problem, the query searched a column for a search phrase and based on if the column has the phrase, it then returns the results, The query is below,
Dim pdb = New ProductDataContext()
Dim query =
From a In pdb.tblUSSeries
Join b In pdb.tblSizes_ On a.Series Equals b.Series
Where
a.Series.ToString().Equals(searchString) Or
b.Description.Contains(searchString) Or Not b.Description.Contains(Nothing)
Order By b.Series, b.OrderCode Ascending
Select New CustomSearch With
{
.Series = a.Series,
.SeriesDescription= a.Description,
.Coolant = a.Coolant,
.Material = a.Material,
.Standard = a.Standard,
.Surface = a.Surface,
.Type = a.Type,
.PointAngle = a.PointAngle,
.DiaRange = a.DiaRange,
.Shank = b.Shank,
.Flutes = b.Flutes,
.EDPNum = b.EDPNum,
.SizesDescription = b.Description,
.OrderCode = b.OrderCode
}
Return query
I think the problem is that, in the table certain rows are NULL, so when it is checking the column for the phrase and it encounters a row that is null it, breaks and returns this error,
The cast to value type 'System.Int32' failed because the materialized value is null. Either the result type's generic parameter or the query must use a nullable type.
I have ran this query against another column that has all the rows populated with data and it returns the results ok.
So my question is how can I write it in VB to query the db with the supplied searchstring and return the results, when some of the rows in the columns have null values.
Any help would be great.

The exception occurs when you make the projection (i.e. select new CustomSearch)
And yes your trying to assign Null to some int property
(Not sure which one of your properties that is)
one of 2 choices :
1) Use nullalbe types for your properties (or just that one property).
2) project with an inline If ( ?? in C#) , I don't know VB so don't catch me on the syntax.
Taking Series just as an example i don't know if it's an int or if that's the problematic property
Select New CustomSearch With
{
.Series = If(a.Series Is Nothing,0, CInt(a.Series))
}
In C#
Select new CustomSearch
{
Series = a.Series ?? 0;
}

Related

How to write Azure storage table queries for non-existent columns

We have a storage table where we want to add a new integer column (It is in fact an enum of 3 values converted to int). We want a row to be required when:
It is an older row and the column does not exist
It is a new row and the column exists and does not match a particular value
When I just use a not equal operator on the column the old rows do not get returned. How can this be handled?
Update
Assuming a comparison always returns false for the non-existent column I tried somethinglike below (the value of the property will be always > 0 when it exists), which does not work either:
If the (Prop GreaterThanOrEqual -1) condition returns false I assume the value is null.
If not then, the actual comparison happens.
string propNullCondition = TableQuery.GenerateFilterConditionForInt(
"Prop",
QueryComparisons.GreaterThanOrEqual,
-1);
propNullCondition = $"{TableOperators.Not}({propNullCondition})";
string propNotEqualValueCondition = TableQuery.CombineFilters(
propNullCondition,
TableOperators.Or,
TableQuery.GenerateFilterConditionForInt(
"Prop",
QueryComparisons.NotEqual,
XXXX));
Note: The table rows written so far do not have "Prop" and only new rows will have this column. And expectation is the query should return all old rows and the new ones only when Prop != XXXX.
It seems that your code is correct, maybe there is a minor error there. You can follow my code below, which works fine as per my test:
Note: in the filter, the column name is case-sensitive.
CloudTableClient tableClient = storageAccount.CreateCloudTableClient();
CloudTable table = tableClient.GetTableReference("test1");
string propNullCondition = TableQuery.GenerateFilterConditionForInt(
"prop1", //note the column name shoud be case-sensitive here.
QueryComparisons.GreaterThanOrEqual,
-1);
propNullCondition = $"{TableOperators.Not}({propNullCondition})";
TableQuery<DynamicTableEntity> propNotEqualValueCondition = new TableQuery<DynamicTableEntity>()
.Where(
TableQuery.CombineFilters(
propNullCondition,
TableOperators.Or,
TableQuery.GenerateFilterConditionForInt(
"prop1",//note the column name shoud be case-sensitive here.
QueryComparisons.NotEqual,
2)));
var query = table.ExecuteQuery(propNotEqualValueCondition);
foreach (var q in query)
{
Console.WriteLine(q.PartitionKey);
}
The test result:
Here is my table in azure:

Struggling with simple boolean WHERE clause

Tired brain - perhaps you can help.
My table has two bit fields:
1) TestedByPCL and
2) TestedBySPC.
Both may = 1.
The user interface has two corresponding check boxes. In the code I convert the checks to int.
int TestedBySPC = SearchSPC ? 1 : 0;
int TestedByPCL = SearchPCL ? 1 : 0;
My WHERE clause looks something like this:
WHERE TestedByPCL = {TestedByPCL.ToString()} AND TestedBySPC = {TestedBySPC.ToString()}
The problem is when only one checkbox is selected I want to return rows having the corresponding field set to 1 or both fields set to 1.
Now when both fields are set to 1 my WHERE clause requires both check boxes to be checked instead of only one.
So, if one checkbox is ticked return records with with that field = 1 , regardless of whether the other field = 1.
Second attempt (I think I've got it now):
WHERE ((TestedByPCL = {chkTestedByPCL.IsChecked} AND TestedBySPC = {chkTestedBySPC.IsChecked})
OR
(TestedByPCL = 1 AND TestedBySPC = 1 AND 1 IN ({chkTestedByPCL.IsChecked}, {chkTestedBySPC.IsChecked})))
Misunderstood the question.
Change the AND to an OR:
WHERE TestedByPCL = {chkTestedByPCL.IsChecked} OR TestedBySPC = {chkTestedBySPC.IsChecked}
Also:
SQL Server does not have a Boolean data type, it's closest option is a bit data type.
The usage of curly brackets suggests using string concatenations to build your where clause. This might not be a big deal when you're handling checkboxes but it's a security risk when handling free text input as it's an open door for SQL injection attacks. Better use parameters whenever you can.

Linq to entities if in select statement

I have this linq query
Dim chiamateAperte = From statoRic In
dbVulcano.StatoRic.Where(Function(s) s.RFStato >= 11 And s.RFStato <= 13 And s.Attuale = 1 And s.RFTecnico = rfTecnico)
From richiesta In
dbVulcano.Richieste.Where(Function(r) r.IDRic = statoRic.RFRic).DefaultIfEmpty()
From cliente In
dbVulcano.Clienti.Where(Function(c) c.IDCliente = richiesta.RFCliente).DefaultIfEmpty()
Select statoRic.ID, statoRic.RFRic, statoRic.RFStato, statoRic.Attuale, richiesta.Descr, cliente.RagSociale, statoRic.DataAss, statoRic.Data, dataf = If(statoRic.DataAss.HasValue, statoRic.DataAss, statoRic.Data), statoRic.OraDalle, statoRic.OraAlle
Order By dataf Descending, statoRic.OraDalle Ascending
It's working fine but I want to add an order condition on "OraDalle" field.
OraDalle it's sort of a time field, but sadly on db it's defined as smallInt (and I cannot change it), so the format is like "800" to say "eight o'clock". This field can be null.
So instead of statoRic.OraDalle I tried this:
orad=if (statoRic.OraDalle.HasValue,statoRic.OraDalle,2359)
And then
Order By dataf Descending, orad Ascending
But it throws an ugly error: cannot cast system nullable 1 to system object of type 'system.nullable'. Only primitive types or enumeration types are supported in this context
Then I tried this:
orad=statoRic.OraDalle.GetValueOrDefault(2359)
But it also throw an error like: linq to entities does not recognize the method 'Int16 GetValueOrDefault(Int16)'
So... how can I achieve what I want? This whole mess is to get a list ordered by time, where null time values are at the bottom (and not on the top, as default). Thank you all!
Instead of if (statoRic.OraDalle.HasValue,statoRic.OraDalle,2359) use if (statoRic.OraDalle,2359)
This is the equivalent of C#´s null-coalescing-operator ??:
statoRic.OraDalle ?? 2359 which was the solution for a similar question.

How do I extract a value from a Linq IQueryable object?

I am new to Linq and have been stumped for several days. I have searched this and several other boards to find the answer but cannot. I have a Linq query that is returning 1 value of int.
Public Function myV()
Dim MR As New MainEntities()
Dim mV = From AspNetUsers In MR.AspNetUsers
Where Context.User.Identity.Name() = AspNetUsers.Email.ToString Select AspNetUsers.VB
Return mV
End Function
If myV = 1 Then
perform other code
End If
But when I try to compare to an Int it says the object cannot be compared. I have tried to convert the IQueryable(of Interger) to Int and cannot. How do I get to the Interger value in the IQueryable object?
The LINQ statement returns an IEnumerable, which is like an array in that it can hold multiple values, even it only happens to have one value in it.
The best way to return a single value is .First(), or .Single() if you want to throw an exception if more than one value exists. (Which one you choose depends on your context.)
Public Function myV()
Dim MR As New MainEntities()
Dim mV = From AspNetUsers In MR.AspNetUsers
Where Context.User.Identity.Name() = AspNetUsers.Email.ToString Select AspNetUsers.VB.First()
Return mV
End Function
Because mV is an IQueryable, you can consider it as a type of list or an array. So you need to get the first value:
If myV.First() = 1 Then
'...
End If
Or more likely you want to do that inside the mV function:
Dim mV = From AspNetUsers In MR.AspNetUsers
Where Context.User.Identity.Name() = AspNetUsers.Email.ToString
Select AspNetUsers.VB
Return mV.First()
You misunderstood the query. Your LINQ executes a SQL Statement that is the follows:
SELECT AspNetUsers.VB
FROM AspNetUsers
WHERE ApsNetUsers.Email = "here the name"
Therefore the query does not return only one VB but a table consisting of one column and multiple rows.
In order to retrieve the first value you have to call .First()
If myV.First() = 1 Then [...]

nhibernate hql subquery : convert null to zero

I am trying to update sum of particular amount from one table as a value in another table, but getting problem when the particular id does not exist in another table :
the hql i have looks like beow:
var session = SessionManager.GetCurrentSession();
var queryString = string.Empty;
queryString += #"update CLiner cl set cl.UnbilledDue =
(select sum(cu.UnbilledAmount) as UnbilledAmount from CUnbilled cu
where cu.AccountNo = cl.AccountNo and cu.FileDate = :fileDate)
where cl.FileDate = :fileDate ";
var query = session.CreateQuery(queryString);
query.SetDateTime("fileDate", new DateTime(2014, 10, 7));
query.ExecuteUpdate();
but its giving exception when the particular account no does not exist in child table and the sum is returned as zero.
i tried changing the subquery select to
select isnull(sum(cu.UnbilledAmount),0) as UnbilledAmount
which as expected is not supported by nhibernate hql. so there a way i can convert null to zero in hql select statement...
Try this:
coalesce(sum(cu.UnbilledAccount), 0)
Reason:
Normally when you wirte a SQL query to prevent NULL you must apply an ISNULL function over the SELECT, in this way:
ISNULL(SELECT sum(...., 0) or COALESCE(SELECT sum(...., 0) (return the same result but COALESCE can applied with more parameter, ISNULL has only two parameters)
but in HQL isn't possible, so you can use COALESCE function to prevent that behaviour.