Compare weirdness when working with LINQ and Entity Framework.
I want to retrieve an ID from my DB and I get this weird message.
I could simply fix it as you can see but I want to understand why this happens.
Question:
Why do I get this error message even if I check with "HasValue" or I use "FirstOrDefault"? It can't be null in my opinion but I obviously miss something.
Add .Value if you are 100% sure the Integer? has a value.
Why do I get this error message even if I check with "HasValue"
Entity Framework just uses the objects you give it. It can't create a new object where OPX_ isn't nullable.
the setOpxRights function presumably takes an Integer as a parameter and Option Strict On won't allow an Integer? to be implicitly converted to an Integer. If you are sure that it will always have a value, pass in cctUser.OPX_Rechte.Value
The compiler is not perfect, we can see that OPX_Rechte will have a value because of the where statment, but for the compiler you are just using a the object cctUser that have an Integer? and it needs an Integer.
Related
I'm working on a program, and I need to be able to change a setting using a combobox. I'm getting
CS0266 Cannot implicitly convert type 'object' to 'FastColoredTextBoxNS.Language'. An explict conversion exists (are you missing a cast?)
Using the code:
{
fastColoredTextBox1.Language = comboBox1.SelectedItem
}
Does anyone know a simple way to fix this? If any more info is needed, I will gladly edit it in.
You must cast to the desired type, since the SelectedItem property returns the unspecific type Object.
fastColoredTextBox1.Language = DirectCast(comboBox1.SelectedItem, FastColoredTextBoxNS.Language)
Note there is also the CType function. In addition to performing type casts it also performs also type conversions. We do not need a conversion here, if the items in the ComboBox are of the required type. DirectCast just means, okay I know that the item with the runtime type Object is of the required type, just take it as such.
See also:
Casting DataTypes with DirectCast, CType, TryCast
Difference between DirectCast() and CType() in VB.NET
I'm using Authorize.net API and they require card expiration field to be formated as "yyyy-mm". We did that with this simple line of code:
expirationDate = model.Year.ToString("D4") & "-" & model.Month.ToString("D2")
and this absolutelly worked. I still have cards stored in the system that were saved using this method! But today I was testing something completelly unrelated, and wanted to add another card, and bam, this code exploded with this exception:
System.InvalidCastException: 'Conversion from string "D4" to type 'Integer' is not valid.'
Inner exception to that one is:
Input string was not in a correct format.
This just... doesn't make sense to me. Why in the world is it trying to convert format specifier (D4) into an integer? What input string? What in the world changed in two days?
The problem is that your are using a Nullable(Of Integer). This is a different structure that does not support the overloads of the ToString method a normal Integer has.
You can view the overloads of the Nullable structure here.
I suggest you use the GetValueOrDefault() method to get the proper Integer and also apply the value you expect in case the value is Nothing.
If it is impossible that a instance with a Nothing set for the year reaches this method you can simply use the Value property.
I still do not fully understand why you get this strange error message. Maybe you could check out what the actual method that is called is? Pointing at the method should give you that information. It can't be Nullable(Of Integer).ToString
Well, I found a workable solution and something of an answer thanks to #Nitram's comment. The type of Year/Month property has been changed from Integer to Integer?. Obviously, this isn't a very satisfying answer because I still don't understand why the nullable int can't be formatted, and yet the code compiles perfectly. The working solution for me has been using static format method on String as so:
expirationDate = String.Format("{0:D4}-{1:D2}", model.Year, model.Month)
This works fine even with nullable types.
I have been asked to find out why an ajax call doest work if date fields are left blank on a web form, finding out was easy, its because the VB function expects an object with a Date type.
I'm going to convert these values to Nullable(Of Date), but I'm reluctant as this is a class that's quite heavily used and I don't want to break anything else.
My thinking however is that everything calling this class must be sending in a correct Date or it would throw an error currently, so I should be ok.
As long as I check for a value using HasValue and get the date out using Value then I shouldn't have any problems, or is there something else I need to consider?
If you change every reference to use the Date's Value property it will be no worse than what you have now. Then you can add the HasValue checks where you need to.
As you seen in this picture below, for some reason my DirectCast wont except ANYTHING for the second argument. It says it requires a type, but, it won't take any object at all!
Thanks for any help! I'm using VB.net so all .net answers are acceptable :)
EDIT
Ok, so apparently I'm not giving it the right kind of type. Could somebody please clarify this? Assuming the type it needs to cast to is gridElement, what should I replace objType with?
DirectCast requires an object prototype (i.e. just giving it the intended class name) rather than a System.Type descriptor object. To cast an object using a System.Type, you will want to utilize CTypeDynamic():
Return CTypeDynamic(createElementByIdAndLayer.MemberwiseClone(), objType)
The error is essentially telling you a class with the type name "objType" does not exist.
Its expecting a "Type", not a "Type Object".
What is the return value of the function?
When I am trying to cast Object obj to Type T, if it can not be cast then there is something wrong.
And after I cast the object I will be looking for working with the cast object.
Rather I will be expecting to get an exception at the place where I will be casting it than say where I will be using that object.
In this sense, is it better to use DirectCast instead of TryCast?
Or am I missing some other significance of using TryCast?
(For C# developers, TryCast is similar to "as" and DirectCast is the equivalent of normal casting. As Mike pointed out in the comments, "as" works for nullable value types, but TryCast doesn't.)
If the value really should be a T, then DirectCast is indeed the right way to go - it fails fast, with an appropriate error.
TryCast is appropriate when it's legitimate for the target to be the "wrong" type. For instance, to get all the Button controls in a container, you could go through the control collection and try to cast each to Button. If it works, you do something with it - if it doesn't, you move on. (With LINQ you can just use OfType for this purpose, but you see what I mean...)
In my experience direct casting is appropriate more often than TryCast - although with generics I find myself casting a lot less often than I used to anyway.
The only difference between the two is that, a TryCast will return a null if it fails, while a DirectCast will throw an exception.
These has implications on how you can handle your program. Personally I prefer not having to throw an exception if the possibility of an improper cast (e.g., text input boxes for user input being cast into numeric types) is pretty high.
I think the others have mentioned the times when you should and shouldn't perform "safe casting" (where you ensure that the cast can succeed before risking an exception). If your program does need to perform safe casting then the TryCast method saves both you and the program some work.
I wasn't aware of the TryCast() function until today, and I feel like a fool for using the 'bad' method of safely casting.
If you did not know about the TryCast() function then you might end up with something like this:
'' wasteful, the TypeOf and DirectCast calls are redundant
If TypeOf obj Is SomeClass Then
someObj = DirectCast(obj, SomeClass)
'' More code
End If
The problem is that this method actually performs two casts (technically I think they're actually type-checks). Using the TryCast and checking if the result is Nothing eliminates the 2nd cast and saves needless work.
'' efficient, only one cast is ever performed and there are no InvalidCastExceptions thrown
someObj = TryCast(obj, SomeClass)
If someObj IsNot Nothing Then
'' More code
End If
Following this pattern lets you avoid having to handle expensive exceptions, and efficiently cast to the correct type.
If your design mandates that the object passed to you MUST be of type T, then assert (as in Debug.Assert) that the cast succeeds in debug builds and run exhaustive unit tests to prove that your implementation follows your design.
With your design proven and tested, you can perfrom the direct cast knowing that it can never fail.