How to check null reference before it throws an exception? - linq

how to check this query if has any Item.
Dim fls = (From fl In FSCHART.fltbars
Where fl.FLT_Value.FLIGHT_ID = local.LEG_Value.FLIGHT_ID
Select fl).First
in another case like:
Dim fls = From fl In FSCHART.fltbars
Where fl.FLT_Value.FLIGHT_ID = local.LEG_Value.FLIGHT_ID
Select fl
for each row in fls
textbox1.text=row.name
next
How to find out if a row is null before an exception error occurs?

For the first version, use FirstOrDefault(), not First()
then
If fls IsNot Nothing
For second version, use Any()
something like
If fls.Any()
But a for each on an empty Enumerable won't raise a Null reference exception...
Now, to avoid NRE in the query, use
Where fl.FLT_Valuefls IsNot Nothing AndAlso fl.FLT_Value.FLIGHT_ID = local.xxx
EDIT :
First check should be
If FSCHART.fltbars.Any()

... where (something) != null. E.g.
Where fl != null &&
fl.FLT_Value != null &&
fl.FLT_Value.FLIGHT_ID = local.LEG_Value.FLIGHT_ID

Related

NullReferenceException when retrieving values from LINQ to DataTable

I have an application that is loading data into a database in a background task. The values are retrieved from a datatable using LINQ, manipulated and stored in a new datatable. I'm getting a NullReferenceException error and I can't figure out why. I'm checking to see if the value coming from the LINQ query is null, and if it is, the variable is assigned properly. If, however, the LINQ query contains a value, I get a NullReferenceException "Object reference not set to an instance of an object" error which really makes no sense to me. What am I doing wrong?
Dim pin = (From u In partdata.AsEnumerable() _
Where u.Field(Of String)("PART_GRP") = sPartType And
u.Field(Of String)("INVT_TYPE").Contains("A")
Select oid = u.Field(Of String)("ID"), Position = u.Field(Of Integer?))
Dim pout = (From u In partdata.AsEnumerable() _
Where u.Field(Of String)("PART_GRP") = sPartType And
u.Field(Of String)("INVT_TYPE").Contains("B") Or u.Field(Of String)("INVT_TYPE").Contains("C")
Select oid = u.Field(Of String)("ID"), Position = u.Field(Of Integer?))
If pin.Count > 0 And pout.Count > 0 Then
For i = 0 To pout.Count - 1
ioidID = pout(i).oid
' Parts In
If pin(i).Position Is Nothing Then ' When "Position" is Null, it works and "" is assigned. When "position" is not null, I get a NullReferenceException error on this line.
spinPosition = ""
Else
spinPosition = pin(i).Position
End If
...
Based on the comments to the question, it appears that pin(i) is Nothing. This would cause the exception when you try to dereference it here:
pin(i).Position
Note that you define pin and pout as two separate collections, unrelated to one another. You check that they both contain at least one value:
If pin.Count > 0 And pout.Count > 0 Then
But you never check that they contain the same number of values. You assume this here:
For i = 0 To pout.Count - 1
If pout ever contains more values than pin, your code will fail.

If list.Find() returns null.code returning exception

If list.Find() retuns null.code returning exception. is there a better way to do it. It is in reference to my previous post .
Link : Linq query returning null when trying to pass a column value from list object
ProcessName = Process().Find(x => x.ProcessID == p.ProcessID).ProcessName ?? String.Empty;
Coalesce the results of Find. If Find returns null (i.e. your ProcessID wasn't found) then you will coalesce the null to an object of anonymous type with a single string property ProcessName. Then either your Process object or the object using the anonymous type will both have the ProcessName property and you can use it in your LINQ select from the original question.
ProcessName = (Process().Find(x => x.ProcessID == p.ProcessID) ?? new { ProcessName = "<unknown>" }).ProcessName;
It's because you are trying to access .ProcessName when .Find() doesn't have anything to return:
Try this:
var matchingProcess = Process().Find(x => x.ProcessID == p.ProcessID);
ProcessName = matchingProcess ? matchingProcess.ProcessName : string.Empty;

How can I check for null values in this linq query where clause

I have a linq query to locate a matching item in a SharePoint library. It works fine if there is a custom property called 'MMSTerm' but if the property is null then obviously my string modifications will fail and error out when it hits x["MMSTerm"]
I will need to use string.replace in my where operation so a null won't be good.
SPListItem item = (from x in Items.OfType<SPListItem>()
where x["MMSTerm"].ToString() == pageReference.ToString()
select x).ToList<SPListItem>().FirstOrDefault();
Hopefully this is an easy one.
You can verify if field exists with SPFieldCollection.ContainsField method
SPListItem item = (from x in Items.OfType<SPListItem>()
where x.Fields.ContainsField("MMSTerm") &&
(x["MMSTerm"] == null ||
x["MMSTerm"].ToString() == pageReference.ToString())
select x).FirstOrDefault();
Also I think fluent API looks better in this case:
SPListItem item = Items.OfType<SPListItem>()
.FirstOrDefault(x =>
x.Fields.ContainsField("MMSTerm") &&
(x["MMSTerm"] == null ||
x["MMSTerm"].ToString() == pageReference.ToString()));
Since calling x["MMSTerm"] throws an exception when "MMSTerm" does not exist, rather than returning null, you should call ContainsField
x.Fields.ContainsField("MMSTerm")
to see if the field is there:
SPListItem item = (from x in Items.OfType<SPListItem>()
where x.Fields.ContainsField("MMSTerm") && x["MMSTerm"].ToString() == pageReference.ToString()
select x).FirstOrDefault();
Since && short-circuits evaluation when x.Fields.Contains("MMSTerm") is false, the x["MMSTerm"] would not be evaluated.
In case the x["MMSTerm"] could contain nulls, you could use the ""+obj trick to avoid null reference exceptions:
var pageRefStr = pageReference.ToString();
SPListItem item = (from x in Items.OfType<SPListItem>()
where x.Fields.ContainsField("MMSTerm") && pageRefStr.Equals(""+x["MMSTerm"])
select x).FirstOrDefault();

deleting a record in linq to sql (vb.net) what is wrong with my code?

I am getting the correct Employee Id in the VarEmpID variable. When I click on delete
It is giving me
Unable to cast object of type 'System.Data.Linq.DataQuery`1[my name space]' to type 'namespace'.
enter code here
Protected Sub radGrid1_DeleteCommand(ByVal source As Object, ByVal e As GridCommandEventArgs) Handles radGrid1.DeleteCommand
Dim VarEmpId As String = (CType(e.Item, GridDataItem)).OwnerTableView.DataKeyValues(e.Item.ItemIndex)("EmpId").ToString()
Using dc1 As New EmployeesDataClassesDataContext()
Dim EmployeeEntry = (From p In dc1.Employees
Where (p.EmpId = VarEmpId)
Select p)
dc1.Employees.DeleteOnSubmit(EmployeeEntry)
dc1.SubmitChanges()
Dim queryResults = (From queryItem In EmployeeEntry Select queryItem).ToList()
If queryResults.Any Then
radGrid1.DataSource = queryResults
radGrid1.DataBind()
End If
End Using
End Sub
dc1.Employees.DeleteOnSubmit(EmployeeEntry)
That method expects an Employee instance. Instead, you passed in an employee query.
Dim EmployeeEntry = ( query )
This is a query, not an entry. Consider calling Enumerable.First to get the first result of the query, and then deleting that.
Modified added Dim EmployeeEntry = (From p In dc1.Employees Where (p.EmpId = VarEmpId) Select p).singleorDefault() After that commented out the queryresults part and binded data again it solved my problem. – SmilingLily

Can't enumerate LinQ results with left join

var itemSet = from item in da.GetList<Models.account>()
join file in objFileStorageList
on item.account_id equals file.parent_id into objFile
from fileItem in objFile.DefaultIfEmpty()
where item.company != null && item.company.company_id == 123
orderby item.updatedDate descending
select
new
{
Id = item.account_id,
RefNo = item.refNo,
StartDate = item.StartDate ,
EndDate = item.EndDate ,
Comment = item.comment,
FileStorageID = fileItem != null ? fileItem.fileStorage_id : -1,
Identification = fileItem != null ? fileItem.identifier : null,
fileName = fileItem != null ? fileItem.file_nm : null
};
It raises error message when I try to enumerate through collection result from Linq query above.
LINQ to Entities does not recognize
the method
'System.Collections.Generic.IEnumerable1[SCEFramework.Models.fileStorage]
DefaultIfEmpty[fileStorage](System.Collections.Generic.IEnumerable1[SCEFramework.Models.fileStorage])'
method, and this method cannot be
translated into a store expression
foreach (var item in itemSet)
{
string itemRef= item.RefNo;
}
Please suggest me any solutions.
Thanks in advance.
I think the problem with this is the following 'from' clause:
from fileItem in objFile.DefaultIfEmpty()
Note that your LINQ query may only be executed at the time the result collection is executed. So while you think your exception is in the foreach, it's actually within your expression. This breaks because the possible null value of objFile.DefaultIfEmpty() cannot cast into an IEnumerable.
Try removing the DefaultIfEmpty call and see what happens.

Resources