简体   繁体   中英

LINQ to SQL Error. - The type can't be converted to nullable value

Sometimes when I use LINQ to SQL I get a message error saying; "The type can't be converted to nullable value".

Does anybody knows the reason?

thanks.

the column in sql is not nullable and you are passing in a value that can be null.

for example passing

 DateTime? createdon 

to a table the requires a createdon datetime.

Consider the following example, table/field:

Customer.CustomerId (int)
Customer.Code (int)

Consider the another table/field:

Sale.CustomerId (nullable<int>)

The field Sale.CustomerId references the field Customer.CustomerId. But the Sale.CustomerId field is nullable. If your LINQ shows like this: Sale.Customer.Code, the Code field can generate a nullable integer value, throwing an error, because in the Sale table the Customer is optional. The Customer anonymous type expecteds an integer value, but in this moment, the value is nullable. For safety, type the field Sale.Customer.Code as int? (nullable integer). Change:

Code = Sale.Customer.Code 

to (int?)

Code = (int?)Sale.Customer.Code

And try again!

some times you want to assign a Nullable values (like int? Or Nullable<int> and etc.) into not null values (like int). To avoid of this exception you must cast your object to Nullable value before assign any value to it.like the below code:

int a = 1; //a is int and not null value
int? b = 2; //b is nullable int
a = b; //with this line code you will see compile error
a = b.value; //this is the correct syntax

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM