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]).
Related
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.
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
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.
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.
I am using the below line of code to check if any of the items in the generic lists is empty
or 0
if (Region.Dept.College[index].Student.Any(
c => c.Age=null ||
c.Name !=null ||
c.code!=null ||
c.Fees!=null ||
c.Gender!=null ||
c.M1!=null ||
c.grade!= null ||
c.caste!= null ||
c.castespecified!= null ||
c.GradeLevel!= null ||
c.Gradelevelspecified!= null ||
c.FeePercent!= 0 ||
c.FeePercentSpecified != null ||
c.StudentRegistrationID!= null)
But even if all the items are empty it still enters the if loop, which is incorrect. please help me to correct this.
Variables are sample
You want to check whether any student has a any null property (i.e. c => c.Age==null || c.Name ==null || .. ) and if so not enter the loop, so it should be:
if(!Region.Dept.College[index].Student.Any(condition))
{
//loop code here, all students valid
}
Currently you are testing for the opposite - you are testing whether any student is valid, not if all are valid (which is equivalent to not any invalid). Also examine your null checks - depending on the data type you need different checks, i.e. string.IsNullOrEmpty() for strings etc.
Also I assume c.Age=null was just a typo, otherwise wouldn't compile.
c => c.Age=null
Should be
c => c.Age==null
You're basically assigning Age to null for all the students.
Looks like you're including null ages by mistake
EDIT: Though, I might offload that validation to a method returning a boolean then just reference the method in the If.
To keep it clean, make a function which takes the object as a parameter, then in that function do all this validation and return a boolean.
Something like AllValuesEmpty
Then, your predicate should just be the result of that function.
This is better practice because later if you want to add something to the object or change how you validate whether or not it's empty you can just change one method rather than having to search for long, complicated If conditions.
EDIT2: Also note that C# makes a distinction between NULL values any empty values. Where NULL indicates "there is no reference to anything which could be used to resolve this" and empty indicates "there is space referenced for this, but there's nothing useful stored there"
Perhaps your properties are initialized with default values in the constructor of your object. Perhaps they're empty but not NULL
You have c => c.Age=null || ...—was that supposed to be c => c.Age != 0 ?
To identify which check is failing, perform them one by one with a breakpoint right after.