c# - Exception: The null value cannot be assigned to a member with type System.Int32 which is a non-nullable value type -
Can anyone explain why this exception is coming in the following LINQ query:
Code> Back to DC (Classification of C. Categorization where CID == Select the Classification ID Classification () {Description = C. Description, PainterID = Convert. ToInt16 (c.ParentId),}). Single & lt; Classification & gt; ();
is DC detacentext, classification is a class in which the intribute is ParentId. In the case of parent field empty in ParentId column SQL Server database is a nullable int, the statement returns invalid operation exceptions.
In other words, why the above query fails and 'int y = convert.OINT16 (empty);' Works?
if
can be c.PartentId
null , Then
Convert.ToInt16 (null) throws an exception.
Since you indicate that the
classification ParentId is an integer, is there any reason that you are using
Convert.ToInt16 instead of a little? Do not you want ToInt32 instead? For that matter, why convert all to? Just:
ParentId = c.ParentId ?? 0
... and just to knit-off, technically you do not need to specify your type at the end of the link expression:
. Single & lt; Classification & gt; ()
You can forget this, because it is determined by the compiler, and just do it:
. Single ()
Update:
Oh, I see, I'm sorry I got your original question wrong I read from Why the question really does:
int y = convert toInt16 (empty);
While working, the same thing in Linq2Sql expression throws an exception.
I do not have a very good answer, except for other things, expression is the same in the view code, t is actually handled by 2 differnet Linq implementation (an interface There may be different backing develations as well).
In this case:
int y = Convert.ToInt16 (empty);
You are making a direct call to convert. ToInt16 This is a narrow
default & lt; T & gt; , where t is the desired type (hence it returns 0 in this case).
However, when a Linq2Sql expression is used in the expression and its launch is assigned to the Linq2Entities or Linq2Sql process. There may be a bug somewhere in that stuff, used as the original Linq2Objects (or whatever you want to call it), it actually works fine:
[ TestMethod] // Exam Public Zero TestLinqToObjects () {var stuff = new list & lt; Int? & Gt; () {tap}; Var y = (Select from Convert to x to ToInt32 (x)). first (); Decide. First (0, Y); }
The above "selection" works, however Linq2Sql or EntityFramework will cause a different implementation of the Linq processor to handle the expression by putting the same Linq expression with the collection; ND is somewhat different to try to assess the expression, or to change some of it to a SQL statement, or there may be other bugs that others do not apply.
I know that does not really solve your problem, but can it help explain it?
Comments
Post a Comment