Getting null string from SQL database - nullpointerexception

I'm trying to pull data from sql database and assigning it to text boxes.
But I get error when there is no data in column (null).
string athleteId = Request.Cookies["LoggedInUser"].ToString();
var athlete = AthleteDAL.GetAthleteByID(athleteId);
if (athlete.AthleteFName != null)
{
TextBoxFirstName.Text = athlete.AthleteFName.ToString();}
I'm getting null point exception on if statement.

you need to have this
if (athlete!=null && athlete.AthleteFName != null)
because athlete may be null and trying to use it (athlete.AthleteFName) is an invalid operation

Related

LINQ generating wrong SQL for empty string

I have the following code:
var approver = _context.approver.Where(x => x.ApproverName != "").Select(x => x.ApproverUserId).Distinct();
And the generated SQL is
SELECT DISTINCT "x"."approveruserid"
FROM "approver" "x"
WHERE (("x"."approvername" <> '') OR "x"."approvername" IS NULL )
I'm expecting the SQL should be
SELECT DISTINCT "x"."approveruserid"
FROM "approver" "x"
WHERE (("x"."approvername" <> '') OR "x"."approvername" IS NOT NULL )
So, the generated SQL is missing the NOT clause and this causes to return wrong result. By the way, I'm using Oracle Database. In Oracle, null equals to empty string.
How to fix it?
[UPDATE]: I'm using
var approver = _context.approver.Where(x => x.ApproverName.Length > 0).Select(x => x.ApproverUserId).Distinct();
as a workaround. But I'm open to another suggestion that can generate the SQL properly for empty string checking.
The generated SQL is correct. You are asking for the string to be something other than "", and null != "".
String.IsNullOrEmpty() is not supported by Linq to SQL but your workaround works fine.
Alternatively you can use something like this:
_context.approver.Where(x => (x.ApproverName ?? "" ) != "")

Linq Query in VB

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;
}

Detecting no results in adodb select query

I'm using ADODB connection in C. The code works more or less fine but I'm getting errors when there is no result for my query and I try to read it. Relevant code:
__object *con, *rec;
con = __object_create("ADODB.Connection");
if(con!=NULL) con->Open("odbc name");
if (con == NULL || con->State==0)
{
return 0;
}
rec= __object_create("ADODB.RecordSet");
sprintf(query, "SELECT SUM(column) FROM table WHERE %s", constraint);
rec->CursorLocation=3;
rec->Open(query, con, 1, 3);
float result = rec->Fields(0); // <- Error here
rec->Close();
__object_delete(rec);
__object_delete(con);
I'm getting error code 80020005 (Type mismatch). The DB column is type float. When there are records that meet the constraint and I get a result everything works fine. But when it matches no records the DB server returns null and I get the error. Fortunately result is set to 0 which is reasonable but I would like to detect this better.
The standard ways (BOF/EOF, Fields->Count, == NULL, ...) all fail. Most code samples I can find are for VB and not C so they are not really helpful.
rec->Fields(0).Value returns a variant, before assigning to the float variable check if the variant represents a VT_NULL which indicates that the data returned is NULL.

Linq to nhibernate - Having where clause problems

I am using linq-to-nhibernate with the following query:
ISession session = GetSession();
var query = from storeZoneStyles in session.Linq<StoreZoneStyle>()
from storeZones in session.Linq<StoreZone>()
where storeZoneStyles.StoreZoneId == storeZones.StoreZoneId && storeZones.StoreCode == storeCode
select storeZoneStyles;
With this query, I only want to get all storeZoneStyles that belong to a storecode. Now when I run this I get the following run-time exception:
Unable to cast object of type 'System.Linq.Expressions.ConstantExpression' to type 'System.Linq.Expressions.LambdaExpression'.
Can somebody help me out please?
I had to use this query instead, because joins are not supported in L2N
var query = from storeZoneStyles in session.Linq<StoreZoneStyle>()
where storeZoneStyles.Zone.StoreCode == storeCode
select storeZoneStyles;

How to make Linq to SQL translate to a derived column?

I have a table with a 'Wav' column that is of type 'VARBINARY(max)' (storing a wav file) and would like to be able to check if there is a wav from Linq to SQL.
My first approach was to do the following in Linq:
var result = from row in dc.Table
select new { NoWav = row.Wav != null };
The problem with the code above is it will retreive all the binary content to RAM, and this isn't good (slow and memory hungry).
Any idea how to have Linq query to translate into something like bellow in SQL?
SELECT (CASE WHEN Wav IS NULL THEN 1 ELSE 0 END) As NoWav FROM [Update]
Thanks for all the replies. They all make sense. Indeed, Linq should translate the != null correctly, but it didn't seem to effectively do it: running my code was very slow, so somehow my only explaination is that it got the binary data transfered over to the RAM.... but maybe I'm wrong.
I think I found a work around anyway somewhere else on stackoverflow: Create a computed column on a datetime
I ran the following query against my table:
ALTER TABLE [Table]
ADD WavIsNull AS (CASE WHEN [Wav] IS NULL Then (1) ELSE (0) END)
Now I'll update my DBML to reflect that computed column and see how it goes.
Are you sure that this code will retrieve the data to RAM?
I did some testing using LINQPad and the generated SQL was optimized as you suggest:
from c in Categories
select new
{
Description = c.Description != null
}
SELECT
(CASE
WHEN [t0].[description] IS NOT NULL THEN 1
ELSE 0
END) AS [Description]
FROM [Category] AS [t0]
What about this query:
var result = from row in dc.Table where row.Wav == null
select row.PrimaryKey
for a list of keys where your value is null. For listing of null/not null you could do this:
var result = from row in db.Table
select new
{ Key = row.Key, NoWav = (row.Wav == null ? true : false) };
That will generate SQL code similar to this:
SELECT [t0].[WavID] AS [Key],
(CASE
WHEN [t0].[Wav] IS NULL THEN 1
ELSE 0
END) AS [NoWav]
FROM [tblWave] AS [t0]
I'm not clear here, your SQL code is going to return a list of 1s and 0s from your database. Is that what you are looking for? If you have an ID for your record then you could just retrieve that single record with the a condition on the Wav field, null return would indicate no wav, i.e.
var result = from row in dc.Table
where (row.ID == id) && (row.Wav != null)
select new { row.Wav };