Display Null from database in asp.net - c#

I want to display every thing in database to asp.net. But some of my value are null and some not. When I load to the page that null it will cause error. May I know how can I fix this problem? My mean is to display everything from database doesn't care it is NULL or having content.
SELECT m.PersonID, m.Picture,m.PersonName, t.title, t.Fileupload, t.contentBody, t.dateInserted FROM person m, thread t WHERE m.PersonID = t.PersonID AND t.threadID = #TID
The t.FileUpload in my database some of row are null and some contain contain. And the error is
system.invalidcastexception unable to cast object of type 'system.dbnull' to type 'system.string'

Use Standard SQL coalesce function.
SELECT a.PersonID,
Coalesce (a.Picture, othercolumn, anothercolumn, 'if all are null') as Picture
from tableA a
it will return the first not null value.
Coalesce in mySQL
or just simply:
Coalesce (a.Picture, '') as Picture
This will prevent invalidcastexception

Related

Why Linq Substring() ignore null value

I just realized that when I request this
Orders.Where(y => y.Sub_Item_Id.Substring(0, 10) != y.Sub_Item_Site_Id.Substring(0, 10))
The query ignore all my null value that may exist in y.Sub_Item_Site_Id. So when I have a value in Sub_Item_Id and null in Sub_Item_Site_Id the query does NOT consider this as !=.
Why?
I also tested the same query with SQL
select
*
from
orders as o
where
LEFT(o.sub_item_id, 10) <> LEFT(o.sub_item_site_id, 10)
And I get the same result. I have all my different value but NOT when I have a value in o.sub_item_id and null in o.sub_item_site_id.
Could you explain how and why SQL and Linq is working like this.
Substring() doesn't ignore null, in your query if one of the strings will be null you will get NullPointerException and if one of the string is shorter than 10 symbols, you will get ArgumentOutOfRangeException:
https://msdn.microsoft.com/library/aka44szs(v=vs.110).aspx
Check your data nad your query.
You may want to add a tag indicating that your LinQ in the background connects to a database to execute SQL there. Without that information, Maksim is correct. In plain Linq-to-Objects C# you would get the appropriate exceptions.
However, as your LinQ is translated and executed as SQL, you just met a surprisingly unintuitive SQL feature: NULL is never equal to anything else. Not even NULL. And NULL is never not equal to anything else. No even a value or another NULL. It just never yields true in a comparison, whatever you compare it to.
You can use the IS syntax to ask if something is NULL. Or you can replace your NULL with a default value before doing your statement. But comparing existing values and NULL will always yield false because NULL is not equal to anything, not even NULL itself.
Relational expressions involving NULL actually yield NULL again. In order to filter null values, you need to use the IS NULL and IS NOT NULL. You can find an answer here.

DATAADAPTERS AND NULLS

I am trying to pass a null to DataAdapter.Fill. My SQL statement accepts nulls but I get a return that nulls are not acceptable.
JUEGO.etreDataSetTableAdapters.CountyTableAdapter etreDataSetCountyTableAdapter = new JUEGO.etreDataSetTableAdapters.CountyTableAdapter();
etreDataSetCountyTableAdapter.Fill(etreDataSet.County, null);
CollectionViewSource CViewSource = ((CollectionViewSource)(this.FindResource("CViewSource")));
CViewSource.View.MoveCurrentToFirst();
the CountryTableAdapter has the SQL Statement below behind it.
SELECT DISTINCT CCODE FROM HH_Match WHERE (#DCODE IS NULL OR DCODE = #DCODE)
but when I pass Null like above it returns a massage that nulls are not allowed. I am working in Visual Studio (C#) 2012. Thanks in advance for the help
You have to configure the TableAdapter manually so that it accepts null.
Therefore click on Parameters in the query property. Select the parameter you want to make optionally (in this case you have only one parameter). On the right side you'll find AllowDbNull. Set this to True and you've arrived.

Checking for nulls in distinct

I have tried a bunch of different ways to do this but every time I try this it throws a null reference exception.
I am trying to filter the values in a field to have a list of the unique values inside that field. It works on fields with no missing values but when i use it on fields that i know to have null values it throws an exception so im assuming that is what i should be filtering for.
The original way i was doing this was just looping through the values and checking if the list of unique values contained the value yet but this was taking a long time and i wanted to harness the power of Linq
List<Graphic> ReturnedGraphics = e.FeatureSet.Features as List<Graphic>;
IEnumerable<string> ValueSet = (
from g in e.FeatureSet.Features
where !uniquevalues.Contains((g.Attributes[_selectedField] == null ? "blank" : g.Attributes[_selectedField].ToString()))
select g.Attributes[_selectedField] == null ? "blank" : g.Attributes[_selectedField].ToString()
) as IEnumerable<string>;
if (ValueSet.Any())
{
uniquevalues.AddRange(ValueSet);
}
I should also add that the reason im adding a range to the list is because there are 5000 values coming in from the server which has a limiter on values to return, however it works for this and shouldn't have an effect on what im trying to do here.
You can't .ToString() null values. Looks like you might be trying to. Candidates for null include lstbxFields.SelectedValue, g.Attributes[someVal]
How about rationalizing your code so that the errors are easier to trap and you're not repeating yourself all over the place?
var selVal = lstbxFields.SelectedValue;
if(selVal == null)
{
//act on this
return; //or throw
}
var selectedValue = selVal.ToString();
var query=
e.FeatureSet.Features
.Select(feature => feature.Attributes[selectedValue])
.Select(attr => attr == null
? "blank"
: attr.ToString())
.Where(attrVal => !uniquevalues.Contains(attrVal));
Your data model is almost certainly "wrong" in the sense that it's very error prone and hard to work with. You should not be converting everything to string but working on the strongly typed objects directly. Doing so will likely fix this bug automatically as it's very likely the NullReferenceException is being thrown when you attempt to ToString a null value.
Not only is it much safer to work on the typed objects, it's also much faster and will result in shorter code.

nHibernate unable to cast Boolean to String

I have the following query:
var query = from item in Session.Query<FactuurItem>()
where item.EnergieType == etype
&& (item.DienstType == null || item.DienstType == DienstType.Onbekend || item.DienstType == dtype)
&& item.IsActive == true
orderby item.Naam
select item;
Which is converted to the following SQL:
select * from [FactuurItem] factuurite0_
where
factuurite0_.EnergieType=?
and (factuurite0_.DienstType is null or factuurite0_.DienstType=? or factuurite0_.DienstType=?)
and case when factuurite0_.IsActive=1 then 'true' else 'false' end=case when ?='true' then 'true' else 'false' end
order by factuurite0_.Naam asc
Which results in the Exception:
{"Unable to cast object of type 'System.Boolean' to type 'System.String'."}
Now for my question: why??
The original query looks ok to me. The SQL, however, does not. Where do the two case-statements originate from? Apparently it tries to convert the property IsActive to a string in SQL, which it fails to do.
EDIT
Ok, found the solution. Nothing wrong with mapping etc., just with how the LINQ query is translated to SQL. In particular, how this line is translated:
&& item.IsActive == true
Somehow, this gets translated into the complex CASE-statement which ultimately results in the exception message. However, the == true-part isn't really necessary. By removing it, the translator no longer gets confused and provides the proper SQL:
factuurite0_.IsActive=1
No more CASE-statement and no more exception.
Ok, found the solution. Nothing wrong with mapping etc., just with how the LINQ query is translated to SQL. In particular, how this line is translated:
&& item.IsActive == true
Somehow, this gets translated into the complex CASE-statement which ultimately results in the exception message. However, the == true-part isn't really necessary. By removing it, the translator no longer gets confused and provides the proper SQL:
factuurite0_.IsActive=1
No more CASE-statement and no more exception.
Using Log4Net at the debug level? In some version of Hibernate and Log4Net there is an incompatibility when turn on logging at the DEBUG level. All you get is this error about 'unable to execute sql cannot cast boolean to string'. Try turning up your logging level to INFO and the problem should go away.

How to short curcit null parameter (SQL)

Hello Friends i have the following query which defeat the very purpose.
A day ago i asked suggestion for to sort circuit the parameter which are null for that i got the suggestion to use
(#firstYrPercent is null OR first_year_percent>=#firstYrPercent) like this to deny null parameter but today when i am running actual query i think that above mentioned idea is of no use.
I am getting sql exception for all those parameter which are null and it is demanding value for those error is this Sql Exception is caught:
"Parameterized Query '(#courseId int,#passoutYear int,#currentBacklog int,#sex int,#eG' expects parameter #currentDegeePercentage, which was not supplied. "
Here is the query please suggest me an alternative:
string cmd = #"SELECT * FROM [tbl_students] WHERE course_id=#courseId
AND branch_id IN(" + branchId + #")
AND (#firstYrPercent is null OR first_year_percent>=#firstYrPercent)
AND (#secondYrpercent is null OR second_year_percent>=#secondYrPercent)
AND (#thirdYrPercent is null OR third_year_percent>=#thirdYrPercent)
AND (#finalYearpercent is null OR final_year_percent>=#finalYearpercent)
AND (#currentDegeePercentage is null OR current_degree_percent>=#currentDegeePercentage)
AND (#passoutYear is null OR passing_year>=#passoutYear)
AND (#currentBacklog is null OR current_backlog<=#currentBacklog)
AND gender=#sex
AND (#eGap is null OR gapin_education<=#eGap)
AND (#highSchoolPercentge is null OR highschool_percentage>=#highSchoolPercentge)
AND (#higherSchoolPercentage is null OR ssc_percentage>=#higherSchoolPercentage)
AND (#grauationPercentage is null OR graduation_percentage>=#grauationPercentage)
AND (#diplomaPercentage is null OR diploma_percentage>=#diplomaPercentage)
AND (#noOfAtkt is null OR number_of_ATKT<=#noOfAtkt)
AND (#date is null OR DOB>=#date)";
You need to make sure you define the #currentDegeePercentage parameter on the Command you are executing - specifically, if you want to pass in that parameter as null, ensure the parameter is added to the command with a value of: DBNull.Value.
If you don't add the parameter to the Command.Parameters collection, or add it but set the value to null (as opposed to DBNull.Value), then you will get the error you are seeing.
The problem is not that the parameter is null but that the parameter is missing. Check for typos (it's "degree", not "degee" [sic]).

Categories