I kept getting the error message below while trying to retrieve data using entity framework and assigning to my custom class Customer
cannot convert source type 'system.nullable' to target type 'int'
CustomerNumber and Route have datatypes of Int32 and the fields in the database allows nulls
select new Customer()
{
AccountListId = j.cost1,
Csr = j.cost2,
CustomerName = j.cost3,
Address = j.cost4,
Telephone = j.cost5,
Contact = j.cost6,
CustomerNumber = j.cost7,
Branch = j.cost8,
Route = j.cost9,
}).ToList<Customer>();
How can I handle this?
Apparently, j.cost7
and j.cost9
are of type Nullable<Int32>
. I am assuming, because you haven't shown us.
Obviously, you can't assign a Nullable<Int32>
to an Int32
type, because, what do you do if the value is null
? The compiler doesn't know. You need to decide what to do in that case, and code accordingly.
Let's say you decide to assign -1
as a default value in case of a null
value in the database, then you can use the null-coalescing operator and do something like this:
select new Customer()
{
AccountListId = j.cost1,
Csr = j.cost2,
CustomerName = j.cost3,
Address = j.cost4,
Telephone = j.cost5,
Contact = j.cost6,
CustomerNumber = j.cost7 ?? -1,
Branch = j.cost8,
Route = j.cost9 ?? -1,
}).ToList<Customer>();
If, what you really want, is to be able to store the null
value if there is one, then change the type of CustomerNumber
and Route
from Int32
to Nullable<Int32>
, or using an alternate syntax: int?
.