Why do I get an 'InvalidCastException' - wpf

private Incident incident = null;
incident = (Incident)(rdc.Incidents.Where(i => i.ID == ID));
I get the following exception:
Unable to cast object of type 'System.Data.Linq.DataQuery`1[WPF.Incident]' to type 'WPF.Incident'.
I need an instance of Incident to use it like this:
IList listInjury = ((IListSource)incident.Incident_Injuries.OrderBy(m => m.Employee.LastName)).GetList();

Try:
incident = rdc.Incidents.First(i => i.ID == ID);

The Where method can return multiple results (probably not in your specific case, but in the general case it could), so you'll need to get the first (and presumably only) result with First method like Mehrdad described

The code
(Incident)(rdc.Incidents.Where(i =>i.ID == ID))
returns a sequence, IEnumerable<Incident> and you are trying to cast that to type of Incident.That's why you're getting InvalidCastException because those types are not compatible. As Mehrdad suggested, you can use First. However, First would throw an exception if the sequence does not contain any elements. This may or may not be desirable. If exception is not desirable, you can call DefaultOrEmpty which would return the default value for that type if the sequence contains no elements. If Incident is a reference type, the default value would be null and you should add a null check in your code and handle that case appropriately.

Related

Mapping returns undefined when calling it through map but will return value with explicit typing

I have a record with some matching data.
Consider this:
{Object.keys(record['matchData']).map((p) => (<p>{p}</p>))}
Will return name, id, alias
Expanding on this, calling it like that:
{Object.keys(record['matchData']).map((p) => (<p>{record['matchData']['name'}</p>))}
Will return 3 rows, each populated with name.
However, calling it like this
{Object.keys(record['matchData']).map((p) => (<p>{record['matchData'][p]}</p>))}
Will crash the page and the result is undefined.
Why does explicitly calling ['name'] works, but [p] (which contains name) does not?

Summing the values of multiple Vectors in the session

In my gatling scenario, I need to check the session for a few entries that will be Vectors of numbers. I can get the Vectors if present, but when I attempt to add them using .sum I get a ClassCastException stating that java.lang.String can't be cast to java.lang.Integer
I've debugged by printing out the value retrieved from the session (Vector(100,200,300)), and even confirmed that the individual elements are Ints. However when I try to add any of them, either with something like values.sum or values(0)+values(1) I get the class cast exception
I'm setting values in the session with checks like
.check(jsonPath("$..payments..paymentAmount").findAll.optional.saveAs("payments"))
.check(jsonPath("$..receipts..receiptAmount").findAll.optional.saveAs("receipts"))
in my app these will always result in things like Vector(100, 200, 300) if the path was there
then later I want to sum all the values in these lists so I have the action
.exec(session => {
def addAmounts(listNames: Array[String]): Int = {
listNames.foldLeft(0)((acc, listName) => {
session(listName).validate[Seq[Int]] match {
case Success(ints) => ints.sum + acc
case Failure(error) => acc
}})
}
val transactionsTotal = addAmounts(Array("payments", "receipts"))
session.set("total",transactionsTotal)
}
As mentioned, this fails on the listName.sum + acc statement - since they're both Ints I'd expect there'd be no need to cast from a string
The Failure case where nothing was stored from the check works fine
I think this is a scala type inference issue - I got it working by manually casting to Int before doing addition

Inserting NULL integer using VB.Net and EF5

Working on an application that relies on an older version of entity, and I'm trying to insert a NULL into an int field. The field in SQL Server is (int, null).
Here's the definition of the object in EF:
<EdmScalarPropertyAttribute(EntityKeyProperty:=false, IsNullable:=true)>
<DataMemberAttribute()>
Public Property application_id() As Nullable(Of Global.System.Int32)
...and here is where I'm trying to set it:
applications.application_id = IIf(IsNumeric(txtAppID.Text), CInt(txtAppID.Text), Nothing)
The error thrown in response is:
An exception of type 'System.InvalidCastException' occurred in ... but was not handled in user code
Additional information: Specified cast is not valid.
I can confirm that this issue is being thrown due to the Nothing portion because previously it was applications.application_id = CInt(txtAppID.Text) and all was fine.
I've tried DBNull.Value instead of Nothing, though the error reads the same. Done a fair bit of research though most issues relate to ES6 or datetime fields, and as such I felt my issue was specific enough to warrant its own question.
Thanks.
The IIf function doesn't short circuit, and therefore always evaluates both the true and false parts, so it's not going to work in that situation. The If keyword does short circuit, but you will probably run into issues with the return type and nullable value types (e.g. Dim x As Integer? = If(False, 1, Nothing) results in x = 0 because the If is returning Integer and not Integer?).
So, I would recommend either using a regular If statement:
If IsNumeric(txtAppID.Text) Then
applications.application_id = CInt(txtAppID.Text)
Else
applications.application_id = Nothing
End If
or you could create a helper function:
Function NullableCInt(value As String) As Integer?
If IsNumeric(value) Then Return CInt(value)
Return Nothing
End Function
and use that:
applications.application_id = NullableCInt(txtAppID.Text)
You can get working If method with casting
Dim temp As Integer
applications.application_id = If(Integer.TryParse(value, temp), temp, DirectCast(Nothing, Integer?))
For better readability you can introduce "default" value
Static DEFAULT_VALUE As Integer? = Nothing
Dim temp As Integer
applications.application_id = If(Integer.TryParse(value, temp), temp, DEFAULT_VALUE)
With Integer.TryParse you need "check/convert" string to integer only once.

Using contains to match two fields

I have a database table which has a bunch of fields including one called Type and another called Code. I also have a list of Type and Code pairs that are encapsulated in a class. Something like this:
public class TypeAndCode
{
public byte Type { get; set; }
public int Code { get; set; }
// overrides for Equals and GetHashCode to compare if Type and Code are equal
}
Now what I need to do is select from the table only those entries who type AND code match an entry in my collection. So, for example, I tried something like this:
var query = myTable.Where(a => myTCList.Contains(new TypeAndCode() { Type = a.Type, Code = a.Code }).ToList();
But it'll give me a NotSupportedException:
Unable to create a constant value of type 'TypeAndCode'. Only primitive types
or enumeration types are supported in this context.
Is there a way to make this work so that I can retrieve from the database only those entries that have a Code and Type that match my list of Code and Type? I'm trying to avoid having to retrieve all the entries (it's a big table) and match them in memory.
I'm aware that I could try something like
var query = myTable.Where(a => listOfTypes.Contains(a.Type) && listOfCodes.Contains(a.Codes))
But that will make some spurious matches where the type and code are from different pairs in my original list.
You can use Any instead:
var query = myTable
.Where(a => myTCList.Any(t => t.Type == a.Type && t.Code == a.Code ))
.ToList();
You should be able to just do this manually without the overloaded methods from your class:
myTCList.Any(x => x.Type == a.Type && x.Code == a.Code)
My ulitmate solution here, in case anybody else encounters a similar problem, was to set up a temporary table that I could write the pairs I wanted to match to which I could them join with the database table. After doing the join and materializing the results, you can delete the temporary table.
Something like:
ctx.myTempTable = (from pair in mypairs
select new myTempTable() { Type = pair.Type, Code = pair.Code }).ToList();
ctx.SaveChanges();
var query = from q in myTable
join t in ctx.myTempTable
on new { q.Type, q.Code } equals new { t.Code, t.Type }
select q;
The whole thing is in a try/catch/finally block with the finally block used to clear up the temporary table(s)

Initial term of field expression must be a concrete SObject: Object

I have just 2 objects and simple query to retrieve the data.
The result of query which is stored in array ccList according to debug output is:
(
CustomThree__c:
{
Name=cusmei3 2,
customOne__c=a005000000IwnOPAAZ,
Id=a025000000FsFGQAA3
},
CustomThree__c:
{
Name=cusmei3 1,
customOne__c=a005000000IwnOUAAZ,
Id=a025000000FsFGLAA3
}
)
As you can see system.debug(ccList[0]) returns:
CustomThree__c:{
Name=cusmei3 2,
customOne__c=a005000000IwnOPAAZ,
Id=a025000000FsFGQAA3
}
But when I try to get Id (or other field) from the array, the error occurs.
Can anyone point out what am I doing wrong?
code
Object[] ccList;
ccList = [SELECT id, name, CustomOne__r.name FROM CustomThree__c];
system.debug(ccList);
system.debug('******************************************');
system.debug(ccList[0]);
system.debug(ccList[0].Id); //this one cause the error
I think you'll have to change the type of ccList from "Object" to "CustomThree__c". This will also give you compile-time checking when you'll try to write ccList[0].SomeNonExistentFieldName__c.
If you can't do it and really need the object that stores result to be generic - I believe this should be SObject?

Resources